NSubstitute ReturnsForAnyArgs 返回 null 但不应该返回 null

Tia*_*goM 5 c# unit-testing nsubstitute

我的测试用例有问题,我试图模拟 my 的返回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);
}
Run Code Online (Sandbox Code Playgroud)

我的测试用例出了什么问题?

Nko*_*osi 2

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

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

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

cacheProvider
    .Fetch(Arg.Any<string>(), Arg.Any<Func<IEnumerable<int>>>())
    .ReturnsForAnyArgs(GetFakeCacheDB());
Run Code Online (Sandbox Code Playgroud)