用N-Unit和Rhino Mocks发出写作单元测试

时间:2016-08-11 22:40:33

标签: c# .net unit-testing nunit rhino-mocks

初级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);

}

1 个答案:

答案 0 :(得分:0)

发生这种情况的原因是mocks.ReplayAll();表达式的放置。我在原帖中添加了正确的测试代码。我希望这可以帮助有同样问题的人,我感谢那些尝试过帮助的人。