You may have been using other frameworks for mocking and stubbing your HTTP requests - also known as using an "Imposter". This post demonstrates how you can easily stub a simple get request using Wiremock. If you want to see how you can use this in a test in combination with ASP.NET, take a look at this post.
The nuget package for Wiremock in C# is called Wiremock.Net and you can install it using your favourite IDE, below is an example in Visual Studio:
The installed package will look something like the following your csproj file:
<ItemGroup>
<PackageReference Include="WireMock.Net" Version="1.5.6" />
</ItemGroup>
You can start a Wiremock Server with the following short line:
var server = WireMockServer.Start(58116);
By calling WireMockServer.Start(58116);
you can start your wiremock server on port 58116
and you can then configure it to return a response for a specific path:
server
.Given(
Request.Create()
.WithPath("/someEndpoint")
.UsingGet()
)
.RespondWith(
Response.Create()
.WithStatusCode(200)
.WithBody("Hello world")
);
In the above we set up Wiremock to return "Hello World" as the body when the path /someEndpoint
is hit. We can test this by using the HttpClient in a small test:
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(
"http://localhost:58116/someEndpoint");
Assert.True(response.IsSuccessStatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("Hello world", body);
In the above we create a new HttpClient and call our wiremock server using http://localhost:58116/someEndpoint
. We assert that the response is successful and that the body is "Hello World". That is all there is to it.
That is all
I hope this showed how easy it is to set up wiremock and start using it, I hope you enjoyed it. If you want an example of mocking a HttpClient call in an ASP.NET controller look here. As always let me know what you think in the comments down below!