Exemplo n.º 1
0
        public async Task weatherApiGetsData()
        {
            // ARRANGE
            var mockOptions = new Mock <IOptions <WeatherApiConfig> >();

            mockOptions.Setup(m => m.Value)
            .Returns(new WeatherApiConfig()
            {
                weatherApiUrl = "http://testapi.com/",
                weatherApiKey = "123456789"
            });

            var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(new FakeWeatherData()))
            })
            .Verifiable();

            var httpClient = new HttpClient(handlerMock.Object);

            var weatherApi = new WeatherApi(mockOptions.Object, httpClient);

            //ACT
            WeatherData result = await weatherApi.getData("Vilnius");

            // ASSERT
            Assert.IsNotNull(result);
            Assert.AreEqual("Vilnius", result.name);
            Assert.AreEqual(200, result.cod);

            var expectedUri = new Uri("http://testapi.com/?appid=123456789&q=Vilnius&units=metric");

            handlerMock.Protected().Verify(
                "SendAsync",
                Times.Exactly(1),
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Get &&
                                               req.RequestUri == expectedUri
                                               ),
                ItExpr.IsAny <CancellationToken>());
        }