c# - NSubstitute ReturnsForAnyArgs 返回 null 但不应该

标签 c# unit-testing nsubstitute

我的测试用例有问题,我试图模拟我的 ICacheProvider 的返回但它总是返回 null .

[Fact]
public void Raise_ShoultReturnTrue_IfItsInCache()
{
    var cacheProvider = Substitute.For<ICacheProvider>();
    cacheProvider.Fetch(Arg.Any<string>(), default(Func<IEnumerable<int>>)).ReturnsForAnyArgs(GetFakeCacheDB());

    //I was expecting the var below to contain the data from GetFakeCacheDB method
    var cacheProviderReturn = cacheProvider.Fetch("anything", returnEmpty); 

    //there is more stuff here but doesnt matter for the question    
}

private HashSet<int> returnEmpty()
{
    return new HashSet<int>();
}

private IEnumerable<int> GetFakeCacheDB()
{
    var cacheData = new List<int>()
                    {
                       57352,
                       38752
                    };    
    return cacheData;
}

public interface ICacheProvider
{
    void Add<T>(string key, T item);
    void Add<T>(string key, T item, DateTime? absoluteExpiry, TimeSpan? relativeExpiry);
    T Fetch<T>(string key, Func<T> dataLookup);
    T Fetch<T>(string key, Func<T> dataLookup, DateTime? absoluteExpiry, TimeSpan? relativeExpiry);
    void Remove<T>(string key);
}

我的测试用例有什么问题?

最佳答案

对模拟方法的参数的配置期望与传递给它的内容不匹配,因此它将返回 null。

您当前的期望值是 default(Func<IEnumerable<int>>)默认为 null ,但在执行模拟时,您传递了一个与配置的期望不匹配的实际函数。

使用 Arg.Any以及第二个参数,使模拟期望在行使时更加灵活。

cacheProvider
    .Fetch(Arg.Any<string>(), Arg.Any<Func<IEnumerable<int>>>())
    .ReturnsForAnyArgs(GetFakeCacheDB());

关于c# - NSubstitute ReturnsForAnyArgs 返回 null 但不应该,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46444709/

相关文章:

c# - 对于 C#,使用 WSSE 纯文本身份验证的 WCF SOAP 使用者?

c# - .Net 中的数据绑定(bind)下拉控件

AutoFixture + NSubstitute 为注入(inject)的自动模拟抛出 NotASubstituteException

c# - 在为单元测试创​​建模拟时,我们是否在自欺欺人?

c# - 如何测试方法是否在特定输入上引发异常

c# - C# 中的隐式数组转换

c# - Google Chrome 以什么格式存储扩展程序安装日期

visual-studio - 如何配置 VS2012 测试运行器来选择和运行 Gallio 单元测试?

android - 使用 Maven 对 Android 进行单元测试

java - 基本扑克程序 - 打印牌组