如何强制void方法从Stub对象返回Void?

pen*_*ake 6 c# unit-testing rhino-mocks mocking

如何在RhinoMocks中强制执行存根对象以在其上返回void方法的void?

举个例子:

public interface ICar 
{
    string Model {get;set;}
    void Horn();
}

ICar stubCar= MockRepository.GenerateStub<ICar>();
stubCar.Expect(c=>c.Horn()).Return( //now what so that 
                                   // it returns nothing as the meth. returns void ? 
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

该方法不能返回值 - 它是一个void方法.CLR不会让它尝试返回一个值.您无需为此进行测试.

你只需要Expect通话.


Geo*_*ker 6

Return()方法对于void方法调用无效.相反,你想要这样的东西:

ICar stubCar= MockRepository.GenerateStrictMock<ICar>();
stubCar.Expect(c=>c.Horn());
stubCar.DoSomethingThatIsSupposedToCallHorn();
stubCar.VerifyAllExpectations();
Run Code Online (Sandbox Code Playgroud)

它会告诉你是否Horn()被召唤.

这就是测试单元测试时调用void方法的方法.您执行以下操作:

  1. 设定期望(Expect())
  2. 调用应该调用期望的方法
  3. 验证是否已调用预期方法.