1

Say I have an interface IFoo which I am mocking. There are 3 methods on this interface. I need to test that the system under test calls at least one of the three methods. I don't care how many times, or with what arguments it does call, but the case where it ignores all the methods and does not touch the IFoo mock is the failure case.

I've been looking through the Expect.Call documentation but can't see an easy way to do it.

Any ideas?

4

3 回答 3

1

You can give rhino mocks a lambda to run when a function get's called. This lambda can then increment a counter. Assert the counter > 1 and you're done.

Commented by Don Kirkby: I believe Mendelt is referring to the Do method.

于 2008-09-10T09:12:53.533 回答
0

不确定这是否能回答你的问题,但我发现如果我需要用 Rhino(或任何类似的框架/库)做任何类似的事情,任何我不知道如何预先做的事情,那么我最好只是创建手动模拟。

如果调用任何方法,创建一个实现接口并将公共布尔字段设置为 true 的类将非常容易,您可以为该类指定一个描述性名称,这意味着(最重要的是)下一个查看代码的人将立即明白它。

于 2008-09-12T09:53:17.477 回答
0

如果我理解正确,您想检查接口是否在三个指定方法中的任何一个上至少调用一次。通过快速参考,我认为你不能在 Rhino Mocks 中做到这一点。

直觉上,我认为您正在尝试编写易碎的测试,这是一件坏事。这意味着被测类的规范不完整。我敦促您仔细考虑设计,以便被测类和测试可以具有已知的行为。

但是,为了对示例有用,您始终可以这样做(但不要这样做)。

[TestFixture]
public class MyTest {

    // The mocked interface
    public class MockedInterface implements MyInterface {
       int counter = 0;
       public method1() { counter++; }
       public method2() { counter++; }
       public method3() { counter++; }
    }

    // The actual test, I assume you have the ClassUnderTest
    // inject the interface through the constructor and
    // the methodToTest calls either of the three methods on 
    // the interface.
    [TestMethod]
    public void testCallingAnyOfTheThreeMethods() {
        MockedInterface mockery = new MockedInterface();
        ClassUnderTest classToTest = new ClassUnderTest(mockery);

        classToTest.methodToTest();

        Assert.That(mockery.counter, Is.GreaterThan(1));
    }
}

(有人检查我的代码,我现在已经从脑海中编写了这个,并且已经有大约一年没有写过 C# 的东西了)

我很想知道你为什么这样做。

于 2008-09-12T10:27:07.317 回答