Moq函数参数



我有一个使用Func参数的单元测试,但我似乎无法使用MOQ。看看StackOverflow上Func参数的其他例子,我认为这应该起作用:

测试代码:

public class PatternManager : IPatternManager
{
private readonly ICacheManager _cacheManager;
private readonly IDataRepo _data;
public PatternManager(ICacheManager cacheManager, IDataRepo dataRepo)
{
_cacheManager = cacheManager;
_data = dataRepo;
}
public List<Pattern> GetAllPatterns()
{
var allPatterns = _cacheManager.Get(() => _data.GetAllPatterns(), nameof(_data.GetAllPatterns));
return allPatterns;
}
public Pattern GetBestPattern(int[] ids)
{
var patternList = GetAllPatterns().Where(w => w.PatternId > 1);
... More code...
}
...
}

public interface ICacheManager
{
T Get<T>(Func<T> GetMethodIfNotCached, string cacheName = null, int? cacheDurationInSeconds = null, string cachePath = null);
}

我得到的不是GetAllPatterns((中的Pattern列表,而是null。

[Test]
public void PatternManager_GetBestPattern()
{
var cacheManager = new Mock<ICacheManager>();
var dataRepo = new Mock<IDataRepo>();
dataRepo.Setup(d => d.GetAllPatterns())
.Returns(GetPatternList());
cacheManager.Setup(s => s.Get(It.IsAny<Func<List<Pattern>>>(), "", 100, "")) // Has optional params
.Returns(dataRepo.Object.GetAllPatterns());
patternManager = new PatternManager(cacheManager.Object, dataRepo.Object);
int[] pattern = { 1, 2, 3};
var bestPattern = patternManager.GetBestPattern(pattern);
Assert.AreEqual(1, bestPattern.PatternId);
}
private static List<Pattern> GetPatternList()
{ 
... returns a list of Pattern
}

这个设置有什么问题?

mock默认返回null,因为设置与调用模拟成员时实际传递的设置不同。

查看在测试成员中调用的内容

//...
var allPatterns = _cacheManager.Get(() => _data.GetAllPatterns(), nameof(_data.GetAllPatterns));
//...

其很可能是CCD_ 1和具有默认为可选默认值的其他可选参数的字符串CCD_。

现在看看测试中设置了什么

//...
cacheManager
.Setup(s => s.Get(It.IsAny<Func<List<Pattern>>>(), "", 100, "")) // Has optional params
.Returns(dataRepo.Object.GetAllPatterns());
//...

空字符串和实际的int值被设置为预期值,而这不是被测试成员实际调用的值。

因此,mock在执行测试时不知道如何处理通过的实际值,因此将默认为null

使用It.IsAny<>重新设置以接受相应参数的任何值

//...
cacheManager
.Setup(s => s.Get<List<Pattern>>(It.IsAny<Func<List<Pattern>>>(), It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<string>()))
.Returns((Func<List<Pattern>> f, string cn, int? cd, string cp) => f()); //Invokes function and returns result
//...

并注意使用委托来捕获CCD_ 5中的参数。这样,就可以像在被测成员中那样调用实际函数。

最新更新