繁体   English   中英

最小起订量:如何模拟具有函数回调作为参数的方法

[英]Moq: How to Mock method with function callback as paramenter

我正在尝试在InMemoryCache类中模拟以下GetOrSet方法。

public class InMemoryCache : ICacheService
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();

            DateTime expireDateTime = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 4, 0, 0).AddDays(1);
            MemoryCache.Default.Add(cacheKey, item, expireDateTime);
        }
        return item;
    }
}

在测试中,我有

var mockCacheService = new Mock<ICacheService>();
mockCacheService.Setup(x => x.GetOrSet..

有人可以帮我填补点点滴滴吗?

我像这样设置

mockCacheService.Setup(x => x.GetOrSet(It.IsAny<string>(), It.IsAny<Func<object>>()))
                .Returns(new Dictionary<string, string> { { "US", "USA"} });

但是,当我这样拨打电话时,它返回null

var countries = _cacheService.GetOrSet("CountriesDictionary", () => webApiService.GetCountries())

这取决于您要测试的内容。 这里有一些例子:

var mockCacheService = new Mock<ICacheService>();

// Setup the GetOrSet method to take any string as its first parameter and 
// any func which returns string as the 2nd parameter
// When the GetOrSet method is called with the above restrictions, return "someObject"
mockCacheService.Setup( x => x.GetOrSet( It.IsAny<string>(), It.IsAny<Func<string>>() ) )
   .Returns( "someObject" );

// Setup the GetOrSet method and only when the first parameter argument is "Key1" and 
// the second argument is a func which returns "item returned by func"
// then this method should return "someOtherObject"
mockCacheService.Setup( x => x.GetOrSet( "Key1", () => "item returned by func") )
   .Returns( "someOtherObject" );

It具有许多不同的方法,例如IsInIsInRangeIsRegex等。请查看哪种方法适合您的需求。

然后,您需要验证模拟内容。 例如,在下面,我要验证是否使用这些确切的参数调用了该方法,并且只调用了一次。 如果使用“ Key1”作为第一个参数以及返回“ func返回的项目”的func进行调用,则此方法将通过。

mockCacheService.Verify( x => x.GetOrSet( "Key1", () => "item returned by func" ), Times.Once() );

编辑1

这个很重要:

您可能知道这一点,但我希望您不要使用它来测试InMemoryCache.GetOrSet方法。 这里的想法是,您正在测试其他一些类,并且在某些条件下,该类最好使用上面的setup方法中的特定设置调用此模拟。 如果您的被测类未使用“ Key1”调用模拟并且未通过返回“ func重调的项目”的函数,则测试将失败。 这意味着被测类中的逻辑是错误的。 由于您正在嘲笑所有内容,因此请不要使用此类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM