Пример #1
0
        public async Task GetCurrentWeatherAsync_CachesForCorrectPeriodOfTime_UsingStubsAndServiceProvider()
        {
            const int expectedMinsToCache = 101;

            var stubCache = new StubDistributedCache();

            var options = new ServiceCollection()
                          .Configure <ExternalServicesConfig>(ExternalServicesConfig.WeatherApi, opt =>
                                                              opt.MinsToCache = expectedMinsToCache)
                          .BuildServiceProvider()
                          .GetRequiredService <IOptionsMonitor <ExternalServicesConfig> >();

            var sut = new CachedWeatherForecaster(new StubWeatherForecaster(), stubCache, options);

            _ = await sut.GetCurrentWeatherAsync();

            Assert.True(stubCache.ItemCached);
            Assert.Equal(expectedMinsToCache, stubCache.CachedForMins);
        }
Пример #2
0
        public async Task GetCurrentWeatherAsync_CachesForCorrectPeriodOfTime()
        {
            const int expectedMinsToCache = 101;

            int minsToCache = -1;

            var forecasterMock = new Mock <IWeatherForecaster>();

            forecasterMock.Setup(x => x.GetCurrentWeatherAsync())
            .ReturnsAsync(new CurrentWeatherResult {
                Description = "This is a weather description"
            });

            var cacheMock = new Mock <IDistributedCache <CurrentWeatherResult> >();

            cacheMock.Setup(x => x.TryGetValueAsync(It.IsAny <string>())).
            ReturnsAsync((false, (CurrentWeatherResult)null));
            cacheMock.Setup(x => x
                            .SetAsync(It.IsAny <string>(), It.IsAny <CurrentWeatherResult>(), It.IsAny <int>()))
            .Callback <string, CurrentWeatherResult, int>((key, result, mins) => minsToCache = mins);

            var optionsMock = new Mock <IOptionsMonitor <ExternalServicesConfig> >();

            optionsMock.Setup(x => x.Get(ExternalServicesConfig.WeatherApi))
            .Returns(new ExternalServicesConfig {
                MinsToCache = expectedMinsToCache
            });

            var sut = new CachedWeatherForecaster(forecasterMock.Object, cacheMock.Object, optionsMock.Object);

            _ = await sut.GetCurrentWeatherAsync();

            cacheMock.Verify(x => x.SetAsync(
                                 It.IsAny <string>(), It.IsAny <CurrentWeatherResult>(), It.IsAny <int>()), Times.Once);

            Assert.Equal(expectedMinsToCache, minsToCache);
        }