【发布时间】:2016-08-11 22:40:32
【问题描述】:
这里是初级 C#/.NET 开发人员,刚刚负责为我今天创建的服务方法编写我的第一个单元测试。我的公司使用 N-Unit 和 Rhino Mocks,所以我现在正在尝试观看 Pluralsight 课程来自学这两个框架。下面是我创建的方法以及我尝试编写的单元测试,以及它产生的错误:(
谁能告诉我我做错了什么?
待测方法:
public bool shouldSubmit(long clientId)
{
bool isEncrypted = clientFeatRepo.hasClientFeat(clientId, FeatEnum.Encrypted);
bool isSeamless = clientFeatRepo.hasClientFeat(clientId, FeatEnum.Seamless);
if (isEncrypted == false && isSeamless == false)
{
return true;
}
return false;
}
单元测试:
public void testShouldSubmit()
{
clientFeatRepo.Stub(x => x.hasClientFeat(111, FeatEnum.NotEncrypted)).Return(false);
clientFeatRepo.Stub(x => x.hasClientFeat(111, FeatEnum.NotSeamless)).Return(false);
bool results = apiPackageService.shouldSubmit(111);
mocks.ReplayAll();
Assert.IsTrue(results);
}
错误:
System.InvalidOperationException : Previous method 'IClientFeatRepo.hasClientFeat(111, NotEncrypted);' requires a return value or an exception to throw.
at Rhino.Mocks.Impl.RecordMockState.AssertPreviousMethodIsClose()
at Rhino.Mocks.Impl.RecordMockState.MethodCall(IInvocation invocation, MethodInfo method, Object[] args)
at Rhino.Mocks.Impl.Invocation.Actions.RegularInvocation.PerformAgainst(IInvocation invocation)
at Rhino.Mocks.Impl.RhinoInterceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IClientFeatRepoProxyaa745bc909574b67a5ccce407ef647a9.IClientFeatRepo.hasClientFeat(Int64 clientId, FeatEnum featEnum)
at MercuryUserWeb.Core.Services.ApiPackageService.shouldSubmit(Int64 clientId) in C:\Users\DFriedland\Documents\Core\Services\ApiPackageService.cs:line 190
at MercuryUserWebTest.Core.Services.ApiPackageServiceTest.testShould() in C:\Users\DFriedland\Documents\Core\Services\ApiPackageServiceTest.cs:line 1210
正确的测试代码:
public void testShouldSubmit()
{
clientFeatRepo.Stub(x => x.hasClientFeat(111, FeatEnum.NotEncrypted)).Return(false);
clientFeatRepo.Stub(x => x.hasClientFeat(111, FeatEnum.NotSeamless)).Return(false);
mocks.ReplayAll();
bool results = apiPackageService.shouldSubmit(111);
Assert.IsTrue(results);
}
【问题讨论】:
-
当你说它不起作用时,你是什么意思?有错误信息吗?
-
请显示包含
shouldSubmit的整个服务类。另外,展示你如何在测试中实例化你的服务和模拟。 -
@yelxe 这个方法所属的服务类非常大(1161 行代码),所以我不能在这里粘贴。它实际上只是我们相当大的代码库中 120 多项服务中的一项。到目前为止,此方法的测试类为 1227 行。好吧,现在是我的测试方法;)
-
@Bassie 是的,有一个错误。谢谢你提醒我。我会把它贴在 OP 上。很抱歉!
-
首先,模拟方法的默认返回值为
default(<type>),因此您可以使用...删除stub其次,您附加的异常通常会在您不附加时引发使用Return方法。你确定你是在你的 UT 上下文中使用这个方法吗?(你的 sn-ps 之间有一个错字......)
标签: c# .net unit-testing nunit rhino-mocks