【问题标题】:RhinoMocks Expect not working as 'expected'RhinoMocks 预期不按“预期”工作
【发布时间】:2018-07-25 14:30:42
【问题描述】:

我有以下测试代码

//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;
}

【问题讨论】:

  • 显示被测代码,包括被测试访问的所有相关成员
  • 虽然我可以假设 SetSomeResource 是做什么的,但您也应该包括在内。
  • 同样基于当前代码你需要在SetSomething被调用时让mock抛出一个错误。

标签: c# unit-testing rhino-mocks


【解决方案1】:

在与 Rhino Mocks API 和基于交互的测试相关的模拟和存根之间存在一些 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

【讨论】:

    猜你喜欢
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2013-05-28
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    相关资源
    最近更新 更多