带有函数参数的接口的最小值设置



我想用Moq 4.14.7写一个UnitTest。测试方法如下:

public IFoo Get(Guid id)
{
Func<IFoo> getData = () => _repository.Get(id);
if (_cache.TryGetAndSet(vaultId, getData, out var result))
{
return result;
}
}

简要说明。我有一个通用缓存类。它检查缓存中是否存在带有传递的guid的实体。如果不是这种情况,则调用存储库。

现在我为缓存设置如下:

_cache.Setup
(
x => x.TryGetAndSet
(
_vaultId,
It.IsAny<Func<IFoo>>(),
out foo
)
)
.Returns(true);

测试到目前为止是有效的,但是我没有达到100%的覆盖率,因为函数没有被覆盖。

是否有比与It.IsAny合作并获得100%覆盖率更好的方法?

捕获传递给成员的实参,并按需要调用函数。

//...
IFoo mockedFoo = Mock.Of<IFoo>();
IFoo foo = null;
_repo.Setup(_ => _.Get(It.IsAny<Guid>()).Returns(mockedFoo);
_cache
.Setup(_ => _.TryGetAndSet(It.IsAny<Guid>(), It.IsAny<Func<IFoo>>(), out foo))
.Returns((Guid vid, Func<IFoo> func, IFoo f) => {
foo = func(); //<-- invoke the function and assign to out parameter.
return true;
});
//...
//Assertion can later verify that the repository.Get was invoked
//Assertion can later assert that foo equals mockedFoo

TryGetAndSet将返回true,而out参数将返回mockedFoo,延迟求值

参考Moq快速入门

最新更新