.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

posted @ 2022-11-12 14:27  Lulus  阅读(530)  评论(0编辑  收藏  举报