.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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值