1+ using System ;
2+ using System . Net ;
3+ using System . Net . Http ;
4+ using System . Threading . Tasks ;
5+ using MockServerClientNet . Model ;
6+ using Xunit ;
7+ using static MockServerClientNet . Model . HttpRequest ;
8+ using static MockServerClientNet . Model . HttpResponse ;
9+
10+ namespace MockServerClientNet . Tests
11+ {
12+ public class CustomHttpClientTest ( MockServerFixture fixture ) : MockServerClientTest ( fixture , HttpClient )
13+ {
14+ private static readonly HttpClient HttpClient = GetHttpClient ( ) ;
15+
16+ [ Fact ]
17+ public async Task ShouldRespondToHttpsRequest ( )
18+ {
19+ // arrange
20+ await SetupExpectation ( MockServerClient , true ) ;
21+
22+ // act
23+ var response = await SendHello ( HttpScheme . Https ) ;
24+
25+ // assert
26+ Assert . Equal ( HttpStatusCode . OK , response . StatusCode ) ;
27+ Assert . Equal ( "{\" message\" : \" hello\" }" , await response . Content . ReadAsStringAsync ( ) ) ;
28+ }
29+
30+ [ Fact ]
31+ public async Task ShouldNotMatchHttpsRequestWhenSecureIsFalse ( )
32+ {
33+ // arrange
34+ await SetupExpectation ( MockServerClient , false ) ;
35+
36+ // act
37+ var response = await SendHello ( HttpScheme . Https ) ;
38+
39+ // assert
40+ Assert . Equal ( HttpStatusCode . NotFound , response . StatusCode ) ;
41+ }
42+
43+ [ Fact ]
44+ public async Task ShouldNotMatchHttpRequestWhenSecureIsTrue ( )
45+ {
46+ // arrange
47+ await SetupExpectation ( MockServerClient , true ) ;
48+
49+ // act
50+ var response = await SendHello ( HttpScheme . Http ) ;
51+
52+ // assert
53+ Assert . Equal ( HttpStatusCode . NotFound , response . StatusCode ) ;
54+ }
55+
56+ private static HttpClient GetHttpClient ( )
57+ {
58+ return new HttpClient ( new HttpClientHandler
59+ {
60+ ServerCertificateCustomValidationCallback = ( msg , cert , chain , errors ) =>
61+ {
62+ Assert . Contains ( "O=MockServer" , cert . Issuer ) ;
63+ return true ;
64+ }
65+ } , false ) ;
66+ }
67+
68+ private static async Task SetupExpectation ( MockServerClient mockServerClient , bool secure )
69+ {
70+ await mockServerClient . ResetAsync ( ) ;
71+
72+ await mockServerClient . When ( Request ( )
73+ . WithSecure ( secure )
74+ . WithMethod ( HttpMethod . Get )
75+ . WithPath ( "/hello" ) ,
76+ Times . Unlimited ( )
77+ ) . RespondAsync ( Response ( )
78+ . WithDelay ( TimeSpan . FromSeconds ( 0 ) )
79+ . WithStatusCode ( 200 )
80+ . WithBody ( "{\" message\" : \" hello\" }" ) ) ;
81+ }
82+
83+ private async Task < HttpResponseMessage > SendHello ( HttpScheme scheme )
84+ {
85+ var host = MockServerClient . ServerAddress ( ) . Host ;
86+ var port = MockServerClient . ServerAddress ( ) . Port ;
87+ return await HttpClient . GetAsync ( new Uri ( $ "{ scheme } ://{ host } :{ port } /hello") ) ;
88+ }
89+ }
90+ }
0 commit comments