Last active
September 7, 2025 23:33
-
-
Save MirzaLeka/585e928a3071ce610ff1242e42b13e52 to your computer and use it in GitHub Desktop.
Dummy integration tests c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public async Task<WeatherForecast>? GetWeatherForecastById(int id) | |
| { | |
| var wf = weatherData.FirstOrDefault(x => x.ID == id); | |
| var httpClient = _httpClientFactory.CreateClient("MyAPI"); | |
| var result = await httpClient.PostAsJsonAsync("/api/some-server", JsonSerializer.Serialize(wf)); | |
| if (result.IsSuccessStatusCode) | |
| { | |
| return wf; | |
| } | |
| return null; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // crate a custom HttpMessageHandler that always returns what you need | |
| public class FakeHttpMessageHandler : HttpMessageHandler | |
| { | |
| private readonly HttpResponseMessage _response; | |
| public FakeHttpMessageHandler(HttpResponseMessage response) | |
| { | |
| _response = response; | |
| } | |
| protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |
| { | |
| return Task.FromResult(_response); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| namespace TestingPractice.Services | |
| { | |
| public interface IWeatherService | |
| { | |
| WeatherForecast? GetWeatherForecastById(int id); | |
| List<WeatherForecast> GetForecasts(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| builder.ConfigureServices(services => | |
| { | |
| // Remove existing IHttpClientFactory | |
| var descriptor = services.SingleOrDefault( | |
| d => d.ServiceType == typeof(IHttpClientFactory)); | |
| if (descriptor != null) services.Remove(descriptor); | |
| // Add a fake IHttpClientFactory | |
| services.AddSingleton<IHttpClientFactory>(sp => | |
| { | |
| // Success case | |
| var successResponse = new HttpResponseMessage(System.Net.HttpStatusCode.OK) | |
| { | |
| Content = new StringContent("{\"status\":\"ok\"}") | |
| }; | |
| var fakeHandler = new FakeHttpMessageHandler(successResponse); | |
| var httpClient = new HttpClient(fakeHandler) | |
| { | |
| BaseAddress = new Uri("http://localhost") | |
| }; | |
| var factory = Substitute.For<IHttpClientFactory>(); | |
| factory.CreateClient("MyAPI").Returns(httpClient); | |
| return factory; | |
| }); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using TestingPractice.Services; | |
| namespace TestingPractice | |
| { | |
| public class Program | |
| { | |
| public static void Main(string[] args) | |
| { | |
| var builder = WebApplication.CreateBuilder(args); | |
| // Add services to the container. | |
| builder.Services.AddControllers(); | |
| // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle | |
| builder.Services.AddEndpointsApiExplorer(); | |
| builder.Services.AddSwaggerGen(); | |
| builder.Services.AddSingleton<IWeatherService, WeatherService>(); | |
| var app = builder.Build(); | |
| // Configure the HTTP request pipeline. | |
| if (app.Environment.IsDevelopment()) | |
| { | |
| app.UseSwagger(); | |
| app.UseSwaggerUI(); | |
| } | |
| app.UseHttpsRedirection(); | |
| app.UseAuthorization(); | |
| app.MapControllers(); | |
| app.Run(); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [Fact] | |
| public async Task GetWeatherForecastById_ReturnsForecast_WhenHttpOk() | |
| { | |
| var response = await _client.GetAsync("/WeatherForecast/GetWeatherForecast/1"); | |
| response.EnsureSuccessStatusCode(); | |
| var forecast = await response.Content.ReadFromJsonAsync<WeatherForecast>(); | |
| Assert.NotNull(forecast); | |
| Assert.Equal(1, forecast!.ID); | |
| } | |
| [Fact] | |
| public async Task GetWeatherForecastById_ReturnsNotFound_WhenHttpFails() | |
| { | |
| // Override IHttpClientFactory with failure response | |
| var factory = new CustomWebApplicationFactory(); | |
| factory.WithWebHostBuilder(builder => | |
| { | |
| builder.ConfigureServices(services => | |
| { | |
| services.AddSingleton<IHttpClientFactory>(sp => | |
| { | |
| var failResponse = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest); | |
| var fakeHandler = new FakeHttpMessageHandler(failResponse); | |
| var httpClient = new HttpClient(fakeHandler) | |
| { | |
| BaseAddress = new Uri("http://localhost") | |
| }; | |
| var factory = Substitute.For<IHttpClientFactory>(); | |
| factory.CreateClient("MyAPI").Returns(httpClient); | |
| return factory; | |
| }); | |
| }); | |
| }); | |
| var client = factory.CreateClient(); | |
| var response = await client.GetAsync("/WeatherForecast/GetWeatherForecast/1"); | |
| Assert.Equal(System.Net.HttpStatusCode.NotFound, response.StatusCode); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.AspNetCore.Hosting; | |
| using Microsoft.AspNetCore.Mvc.Testing; | |
| using Microsoft.Extensions.DependencyInjection; | |
| using NSubstitute; | |
| using TestingPractice; | |
| using TestingPractice.Services; | |
| using Program = TestingPractice.Program; | |
| namespace IntegrationTests | |
| { | |
| public class TesttingPracticeApplicationFactory : WebApplicationFactory<Program> | |
| { | |
| protected override void ConfigureWebHost(IWebHostBuilder builder) | |
| { | |
| builder.ConfigureServices(services => | |
| { | |
| var mockService = Substitute.For<IWeatherService>(); | |
| // Mock each service method | |
| mockService.GetForecasts().Returns(new List<WeatherForecast> | |
| { | |
| WeatherForecast.ToForecast(1, DateOnly.FromDateTime(DateTime.Now), 42, "Mocked Hot"), | |
| WeatherForecast.ToForecast(2, DateOnly.FromDateTime(DateTime.Now), 0, "Mocked Cold"), | |
| WeatherForecast.ToForecast(3, DateOnly.FromDateTime(DateTime.Now), 20, "Mocked Warm") | |
| }); | |
| mockService.GetWeatherForecastById(1).Returns( | |
| WeatherForecast.ToForecast(1, DateOnly.FromDateTime(DateTime.Now), 42, "Mocked Hot") | |
| ); | |
| services.AddSingleton(mockService); | |
| }); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.AspNetCore.Mvc; | |
| using TestingPractice.Services; | |
| namespace TestingPractice.Controllers | |
| { | |
| [ApiController] | |
| [Route("[controller]")] | |
| public class WeatherForecastController(ILogger<WeatherForecastController> logger, IWeatherService weatherService) : ControllerBase | |
| { | |
| private readonly ILogger<WeatherForecastController> _logger = logger; | |
| private readonly IWeatherService _weatherService = weatherService; | |
| [HttpGet("GetAllWeatherForecasts")] | |
| public ActionResult<IEnumerable<WeatherForecast>> GetForecasts() | |
| { | |
| return _weatherService.GetForecasts(); | |
| } | |
| [HttpGet("GetWeatherForecast/{id}")] | |
| public ActionResult<WeatherForecast> GetOneForecast([FromRoute] int id) | |
| { | |
| if (id < 1) return BadRequest(); | |
| var forecast = _weatherService.GetWeatherForecastById(id); | |
| if (forecast == null) return NotFound(); | |
| return forecast; | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Net; | |
| using System.Net.Http.Json; | |
| using TestingPractice; | |
| namespace IntegrationTests | |
| { | |
| public class WeatherForecastController_WithMockedService | |
| : IClassFixture<TesttingPracticeApplicationFactory> | |
| { | |
| private readonly HttpClient _client; | |
| public WeatherForecastController_WithMockedService(TesttingPracticeApplicationFactory factory) | |
| { | |
| _client = factory.CreateClient(); | |
| } | |
| [Fact] | |
| public async Task GetAllWeatherForecasts_ReturnsMockedData() | |
| { | |
| var response = await _client.GetAsync("/WeatherForecast/GetAllWeatherForecasts"); | |
| response.EnsureSuccessStatusCode(); | |
| var forecasts = await response.Content.ReadFromJsonAsync<List<WeatherForecast>>(); | |
| Assert.Equal(response.StatusCode, HttpStatusCode.OK); | |
| Assert.NotEmpty(forecasts); | |
| } | |
| [Fact] | |
| public async Task GetWeatherForecast_ById_ReturnsCorrectForecast() | |
| { | |
| var response = await _client.GetAsync("/WeatherForecast/GetWeatherForecast/1"); | |
| response.EnsureSuccessStatusCode(); | |
| var forecast = await response.Content.ReadFromJsonAsync<WeatherForecast>(); | |
| Assert.NotNull(forecast); | |
| Assert.Equal(1, forecast!.ID); | |
| } | |
| [Fact] | |
| public async Task GetWeatherForecast_InvalidId_ReturnsBadRequest() | |
| { | |
| var response = await _client.GetAsync("/WeatherForecast/GetWeatherForecast/0"); | |
| Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); | |
| } | |
| [Fact] | |
| public async Task GetWeatherForecast_InvalidId_ReturnsNotFound() | |
| { | |
| var response = await _client.GetAsync("/WeatherForecast/GetWeatherForecast/999"); | |
| Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| namespace TestingPractice.Services | |
| { | |
| public class WeatherService: IWeatherService | |
| { | |
| private readonly List<WeatherForecast> weatherData = []; | |
| private readonly IHttpClientFactory _httpClientFactory; | |
| public WeatherService(IHttpClientFactory httpClientFactory) | |
| { | |
| _httpClientFactory = httpClientFactory; | |
| weatherData.Add(WeatherForecast.ToForecast(1, DateOnly.FromDateTime(DateTime.Now), 35, "Hot")); | |
| weatherData.Add(WeatherForecast.ToForecast(2, DateOnly.FromDateTime(DateTime.Now), 23, "Warm")); | |
| weatherData.Add(WeatherForecast.ToForecast(3, DateOnly.FromDateTime(DateTime.Now), 19, "Mild")); | |
| weatherData.Add(WeatherForecast.ToForecast(4, DateOnly.FromDateTime(DateTime.Now), 10, "Chilly")); | |
| weatherData.Add(WeatherForecast.ToForecast(5, DateOnly.FromDateTime(DateTime.Now), 0, "Cold")); | |
| } | |
| public List<WeatherForecast> GetForecasts() | |
| { | |
| return weatherData; | |
| } | |
| public WeatherForecast? GetWeatherForecastById(int id) | |
| { | |
| return weatherData.FirstOrDefault(x => x.ID == id); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment