-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValuesControllerTest.cs
More file actions
83 lines (70 loc) · 2.99 KB
/
ValuesControllerTest.cs
File metadata and controls
83 lines (70 loc) · 2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using HttpClientLab;
using Microsoft.AspNetCore.Mvc.Testing;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace Api.IntegrationTests
{
public class ValuesControllerTest : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly ITestOutputHelper _output;
private readonly WebApplicationFactory<Startup> _factory;
public ValuesControllerTest(ITestOutputHelper output, WebApplicationFactory<Startup> factory)
{
_output = output;
_factory = factory;
}
[Fact]
public async Task SetupDefaultBehaviourOfSpecificClient()
{
// Arrange
var client = _factory
.WithHttpClientBehaviour(out var httpClientBehaviour)
.CreateClient();
var gitHubClientBehaviour = httpClientBehaviour
.SetupForClient("GitHubClient") // or .SetupForClient<GitHubClient> or .SetupForAnyClient()
.ForRequest(req => req.Method == HttpMethod.Get) // direct access to the HttpRequestMessage
// or .ForAnyRequest()
.Returns(new HttpResponseMessage(HttpStatusCode.OK) // return simply a HttpResponseMessage
{
Content = new StringContent("Hello world!")
});
// Act
var response = await client.GetAsync("/sample");
// Print all http requests to get helpful info on failure
httpClientBehaviour.WriteHttpRequests(_output);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var content = await response.Content.ReadAsStringAsync();
Assert.Equal("Hello world!", content);
}
[Fact]
public async Task SetupDifferentBehaviours()
{
// Arrange
var client = _factory
.WithHttpClientBehaviour(out var httpClientBehaviour)
.CreateClient();
var gitHubClientBehaviour = httpClientBehaviour.SetupForClient<GitHubClient>();
gitHubClientBehaviour
.ForRequest(req => req.Method == HttpMethod.Get)
.Returns(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Hello world!")
});
gitHubClientBehaviour
.ForRequest(req => req.Method == HttpMethod.Post)
.Returns(new HttpResponseMessage(HttpStatusCode.Accepted));
// Act
var getResponse = await client.GetAsync("/sample");
var postResponse = await client.PostAsync("/sample", null);
// Print all http requests to get helpful info on failure
httpClientBehaviour.WriteHttpRequests(_output);
// Assert
Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
Assert.Equal(HttpStatusCode.Accepted, postResponse.StatusCode);
}
}
}