A C# .NET based, lightweight stub server that mimics the functionality of an external service, commonly used by microservices.
- Test locally system and integration tests of system components
- Reduce the dependency on complex and/or expensive test environments
- Per-request conditional responses
- Recording requests
- Easy to use
By using contract testing1 in integration tests for projects with dependencies on external services, the stub server can provide configurable responses for requests made to these services. Each request is recorded and can be validated as part of these integration tests.
Note
In discussions of integration tests, the tested project is frequently called "SUT", the System Under Test in short.
The stub server creates a in-memory web host for the external service to handle the requests and responses for the external service made by the SUT. Creating the stub server can be done within a custom WebApplicationFactory
2 that might be available in the testproject for integration testing the SUT. An example of a custom WebApplicationFactory
can be found in the example testproject.
Setup StubServer
in a custom WebApplicationFactory
Add the initialization of the stub server in the constructor of your custom WebApplicationFactory
.
_stubServer = new StubServer();
Add proxy methodes for adding responses to the StubServer
.
public Task<ResponseSetup> AddResponseSetupAsync(ResponseSetup responseSetup, CancellationToken cancellationToken = default)
=> _stubServer.AddResponseSetupAsync(responseSetup, cancellationToken);
public Task AddResponsesSetupAsync(IEnumerable<ResponseSetup> responseSetups, CancellationToken cancellationToken = default)
=> _stubServer.AddResponsesSetupAsync(responseSetups, cancellationToken);
Add proxy methode for reading requests from the StubServer
.
public Task<IEnumerable<ReceivedRequest>> FindReceivedRequestsAsync(ReceivedRequestSearchParams searchParams, CancellationToken cancellationToken = default)
=> _stubServer.FindReceivedRequestsAsync(searchParams, cancellationToken);
Add proxy methodes for removing responses and received requests from the StubServer
.
public Task ClearResponsesSetupAsync(CancellationToken cancellationToken = default)
=> _stubServer.ClearResponsesSetupAsync(cancellationToken);
public Task ClearReceivedRequestsAsync(CancellationToken cancellationToken = default)
=> _stubServer.ClearReceivedRequestsAsync(cancellationToken);
Override the Dispose
since the StubServer
is a disposable object.
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_stubServer.Dispose();
}
}
Override the CreateHost
of the WebApplicationFactory to configure the base address of the used external service.
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) =>
{
context.Configuration["ExternalApi"] = _stubServer.BaseAddressStub.ToString();
});
base.ConfigureWebHost(builder);
}
Create a test class that implements a IClassFixture<> interface referencing the custom WebApplicationFactory
to share object instances across the tests in the class.
public class WeatherForecastTests : IClassFixture<ExampleWebApplicationFactory<Program>>
In the constructor of the test class use the factory to create the HttpClient
and clear the ResponseSetup
and ReceivedRequest
data from the StubServer
public WeatherForecastTests(ExampleWebApplicationFactory<Program> factory)
{
_factory = factory;
_httpClient = _factory.CreateClient();
_factory.ClearResponsesSetupAsync();
_factory.ClearReceivedRequestsAsync();
}
A typical test uses the factory to setup the response and process the request through the HttpClient
. The request to the external service can be validated.
[Fact]
public async Task GetAllWeatherForecasts()
{
static IEnumerable<WeatherForecast> GetItems()
{
for (var i = 0; i < NumberOfItems; i++)
{
yield return GenerateWeatherForecast(i);
}
}
// Arrange
var expected = GetItems().ToList();
var responseSetup = new ResponseSetup
{
Path = "/external/api/weatherforecast",
HttpMethods = [HttpMethod.Get.ToString()],
ReturnStatusCode = HttpStatusCode.OK,
Response = expected
};
await _factory.AddResponseSetupAsync(responseSetup);
var expectedReceivedRequests = new List<ReceivedRequest>
{
new(responseSetup.Path, responseSetup.HttpMethods[0], responseSetup.Query, responseSetup.Headers, string.Empty, true)
};
// Act
var response = await _httpClient.GetAsync("/weatherforecast");
// Assert
var actual = await response.Content.ReadFromJsonAsync<IEnumerable<WeatherForecast>>();
actual.Should().BeEquivalentTo(expected);
var actualReceivedRequests = await _factory.FindReceivedRequestsAsync(new ReceivedRequestSearchParams("/external/api/weatherforecast", [HttpMethod.Get.ToString()]));
actualReceivedRequests.Should().BeEquivalentTo(expectedReceivedRequests, options => options
.Excluding(_ => _.Headers)
.Excluding(_ => _.Id)
.Excluding(_ => _.CreatedDateTime));
}
- Prepare the
ResponseSetup
:- Set
Path
andHttpMethods
to a partial path and HttpMethod of the expected request used by the external service. - Set
ReturnStatusCode
to the desired HttpStatusCode. - Set
Response
to the desired reponse of the external service.
- Set
- Add the
ResponseSetup
to theStubServer
with the methodAddResponseSetupAsync
Tip
Multiple ResponseSetup
can be added in 1 call with the method AddResponsesSetupAsync
!
- Process the request to the SUT using the
HttpClient
- Verify the response from the SUT
- Verify the request made to the external service
- Use the method
FindReceivedRequestsAsync
to locate the request made to the external service. The request can be found on a combination ofPath
,HttpMethod
, andQuery
.
- Use the method
Important
ReceivedRequest
can only be found when there is a matching ResponseSetup
1.1.0
- Removed obsolete methods in
StubServer
:CreateApiService<TApiService>
CreateApiService(type type>)
- Moved the folder
Services
to the folderInternal
, including classes - Updated access modifier for classes in the folder
Services
frompublic
tointernal
. The following classes are impacted:Results/ApiServiceResult
Results/ApiServiceResult<TModel>
ApiService
ReceivedRequestApiService
SetupResponseApiService
- Change access modifier for class
UriExtensions
frompublic
tointernal
and moved the class to the folderInternal
- Removed interface
IApiResult
1.0.3
- Change the default for the usage of the development certificate in the
StubServer
fromtrue
tofalse
- Changed constructor of
StubServer
so that users can chose a certificate used by theStubServer
and how to handle this certificate in theHttpClient
- Add methods for add and remove
ResponseSetup
items to theStubServer
- Add methods for find and remove
ReceivedRequest
to theStubServer
- [Deprecated] methods in
StubServer
:CreateApiService<TApiService>
CreateApiService(type type>)