【问题标题】:How to create stub, that throws exception on all calls in Rhino mocks?如何创建存根,在 Rhino 模拟中的所有调用上引发异常?
【发布时间】:2012-05-29 23:02:27
【问题描述】:

是否可以使用 Rhino Mocks 创建一个存根,为所有调用抛出异常?

public interface IMyIF
{
    // Some methods
}

[TestClass]
public class MyTestClass
{
    [TestMethod()]
    public void MyTest()
    {
        MockRepository mocks = new MockRepository();
        IMyIF stb = mocks.Stub<IMyIF>();

        // Somehow set stb to throw some exception on every method call
        // without knowing all the methods and overloads in IMyIF interface

        // use stb to test something
    }
}

【问题讨论】:

    标签: .net unit-testing rhino-mocks stub


    【解决方案1】:
    var stb = MockRepository.GenerateStrictMock<IMyIF>();
    

    【讨论】:

    • 现在对我来说已经足够好了,但是如果我想抛出特定的异常怎么办?
    • 我认为 Rhino Mocks 不可能做到这一点。
    • 为什么要创建存根呢?改为传递null
    • 空值被测代码的行为不同。
    【解决方案2】:

    很奇怪的要求。你想测试什么?如果您正在测试接口IFoo 的方法Bar 在您的测试类调用它时抛出一些异常,那么只需在方法Bar 上设置此期望。不要一次测试所有方法。

    这将使您的测试集中在 sut 和依赖项之间的一种特定交互上(我会这样做):

    var mock = MockRepository.GenerateMock<IMyIF>();
    mock.Expect(m => m.Foo()).Throw(new MyCustomException());
    sut.Exercise(mock);
    

    这将抛出 ExpectationViolationException:

    var mock = MockRepository.GenerateStrictMock<IMyIF>();
    sut.Exercise(mock);
    

    这将抛出 NullreferenceException:

    sut.Exercise(null);
    

    您还可以创建继承自IMyIF 的类MyIFStub。右键单击接口名称并选择实现接口。 Visual Studio 将生成接口的子成员,这将引发 NotImplementedException。如果需要,您可以更改存根实现:

    public class MyIFStub : IMyIF
    {    
        public void Foo()
        {
           throw new NotImplementedException();
        }
    
        // other members
    }
    

    【讨论】:

    • 我正在测试 MyClassUnderTest,这取决于 IMyIF。我不想依赖于实际调用 IMyIf 中的方法重载(它可以更改,但测试的含义不会),我想测试,当调用 MyClassUnderTest 的 MethodUnderTest 和 IMyIF 时,该函数依赖,失败,MethodUnderTest 从这种情况中恢复。
    • 但您不会想到,MethodUnderTest 会调用 IMyIF 的任何随机成员,对吗?
    • 其实我不在乎会调用哪一个。所有方法都做同样的事情,唯一不同的是一些额外的信息参数,对于这个测试来说,这无关紧要。
    猜你喜欢
    • 2012-05-05
    • 2013-08-25
    • 1970-01-01
    • 2020-07-08
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多