RhinoMocks预期无法如预期般运作

时间:2018-07-25 14:30:42

标签: c# unit-testing rhino-mocks

我有以下测试代码

//setup the mock
SomeResource mock = MockRepository.GenerateMock<SomeResource>();
mock.Stub(m => m.GetNumOfResources()).Return(1);
mock.Stub(m => m.SomeProp).Return(SomeEnum.YO);
mock.Expect(m => m.SomeProp).Repeat.Once();
mock.Replay();

//execute
SomeClass sc = new SomeClass();
sc.SetSomeResource(mock);
sc.MethodToTest();

//verify
mock.VerifyAllExpectations();

我想验证是否已访问SomeProp。每当我调试代码时,我都可以看到正在访问SomeProp,但是我在上面设置的期望正在测试中引发异常,但事实并非如此。我是Rhino Mocks的新手,所以我显然没有正确设置某些内容,但看不到什么。有什么想法吗?

编辑:这基本上是我正在测试的代码/逻辑:

private bool MethodToTest()
{
    bool ret= false;

    if (resource == null)
    {
        try
        {
            resource = new SomeResource();
        }
        catch (Exception e)
        {
            //log some error
        }
    }

    if (resource != null && resource.GetNumResources() > 0)
    {
        bool ok = true;

        try
        {
            resource.SetSomething("blah");
        }
        catch (Exception)
        {
            ok = false;

            // Test that SomeProp was accessed here
            SomeEnum val = resource.SomeProp;
        }

        ret = ok;
    }


    return ret;
}

1 个答案:

答案 0 :(得分:2)

模拟和存根之间的一些API混淆,因为它们与Rhino Mocks API和基于交互的测试有关

//Arrange
SomeObj mock = MockRepository.GenerateMock<SomeObj>();
mock.Expect(_ => _.GetNumOfThings()).Return(1);
mock.Expect(_ => _.SetSomething(Arg<string>.Any())).Throw(new Exception());
mock.Expect(_ => _.SomeProp).Return(SomeEnum.YO).Repeat.Once();
SomeClass sc = new SomeClass();
sc.SetSomeResource(mock);

//Act
sc.MethodToTest();

//Assert
mock.VerifyAllExpectations();

引用Rhino Mocks - Stub .Expect vs .AssertWasCalled