.NET & Nsubstitute 根据条件模拟返回值

您所在的位置:网站首页 jeecgframework .NET & Nsubstitute 根据条件模拟返回值

.NET & Nsubstitute 根据条件模拟返回值

#.NET & Nsubstitute 根据条件模拟返回值| 来源: 网络整理| 查看: 265

有时我们单元测试的时候,期待我们通过Nsubstitute模拟的方法可以根据不同的入参、不同的逻辑,返回不同的结果。 事实上,Nsubstitute 支持通过Function的方式返回指定值。 例子代码如下

teacherManager .Insert(Arg.Any()) .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 functionMVC4 Unit test NSubstitute Could not find a call to return from

学习技术最好的文档就是【官方文档】,没有之一。 还有学习资料【Microsoft Learn】、【CSharp Learn】、【My Note】。【推荐】按钮。 如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3