public async Task Setup_UsingDirectlyAnyMockingFramework() { // create an instance of IHttpClientBehaviour or mock it with your favorite mocking library var mockedHttpClientBehaviour = new Mock <IHttpClientBehaviour>(); // Arrange var client = _factory .WithHttpClientBehaviour(mockedHttpClientBehaviour.Object) .CreateClient(); mockedHttpClientBehaviour.Setup(x => x.Handle(It.IsAny <HttpRequestMessage>(), It.IsAny <string>())) .Returns(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Hello world!") }); // Act var response = await client.GetAsync("/sample"); // Print all http requests to get helpful info on failure mockedHttpClientBehaviour.WriteHttpRequests(_output); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("Hello world!", content); }
/// <summary> /// Configure the HttpClientFactory of the in-memory testing environemnt to use the mocked behaviour returned as out parameter. /// </summary> /// <typeparam name="TEntryPoint">The type of the application entry point, usually Startup.</typeparam> /// <param name="factory">The WebApplicationFactory instance.</param> /// <param name="httpClientBehaviour">The behaviour of the HttpClients to be configured.</param> /// <returns></returns> public static WebApplicationFactory <TEntryPoint> WithHttpClientBehaviour <TEntryPoint>( this WebApplicationFactory <TEntryPoint> factory, out Mock <IHttpClientBehaviour> httpClientBehaviour) where TEntryPoint : class { httpClientBehaviour = new Mock <IHttpClientBehaviour>(MockBehavior.Strict); return(factory.WithHttpClientBehaviour(httpClientBehaviour.Object)); }