我的测试用例有问题,我试图模拟我的 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/