用N-Unit和Rhino mock编写单元测试
本文关键字:单元测试 mock Rhino N-Unit | 更新日期: 2023-09-27 18:02:16
初级c#/。我是。NET开发人员,刚刚被指派为我今天创建的一个服务方法编写我的第一个单元测试。我的公司使用N-Unit和Rhino mock,所以我现在正在尝试观看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);
}
发生这种情况的原因是mocks.ReplayAll();
表达式的位置。我将正确的测试代码添加到我的原始帖子中。我希望这篇文章能帮助到有同样问题的人,我感谢那些试图帮助我的人。