.NET & Nsubstitute 根据条件模拟返回值
有时我们单元测试的时候,期待我们通过Nsubstitute
模拟的方法可以根据不同的入参、不同的逻辑,返回不同的结果。
事实上,Nsubstitute
支持通过Function的方式返回指定值。
例子代码如下
teacherManager
.Insert(Arg.Any<Teacher>())
.Returns(parameters =>
{
var teacher = parameters[0] as Teacher;
if (teacher == null)
return null;
if (teacher.Name == "test teacher")
return null;
if (teacher.Age > 100)
return null;
return teacher;
});
这里我们模拟了Insert
方法,添加了一些判断,比如Age大于100,返回NULL。
根据MVC4 Unit test NSubstitute Could not find a call to return from,需要注意将模拟的方法Insert
设置为virtual
。
否则会报错:
NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException : Could not find a call to return from.
Make sure you called Returns() after calling your substitute (for example: mySub.SomeMethod().Returns(value)),
and that you are not configuring other substitutes within Returns() (for example, avoid this: mySub.SomeMethod().Returns(ConfigOtherSub())).
If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member.
Return values cannot be configured for non-virtual/non-abstract members.
Correct use:
mySub.SomeMethod().Returns(returnValue);
Potentially problematic use:
mySub.SomeMethod().Returns(ConfigOtherSub());
Instead try:
var returnValue = ConfigOtherSub();
mySub.SomeMethod().Returns(returnValue);
示例代码
TeacherServiceMockWithFunctionUnitTest
参考资料
Return from a function
MVC4 Unit test NSubstitute Could not find a call to return from
学习技术最好的文档就是【官方文档】,没有之一。
还有学习资料【Microsoft Learn】、【CSharp Learn】、【My Note】。
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的【推荐】按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。