我试图测试这个非常简单的方法:
public IBus Bus { get; set; }
public void SendData(OrderHeader order)
{
if (Bus == null)
throw new ArgumentNullException("Bus");
Bus.Publish<UpdateOrder>(msg =>
{
msg.EventId = Guid.NewGuid();
msg.EventTime = DateTime.Now;
msg.Order = order;
});
}
为了测试已调用Bus.Publish,我尝试了3种不同的方法,但它们都不起作用:/ 有人能帮我理解这里发生了什么吗?我做错了什么?
[Fact]
public void SendData_PassingOrderHeader_PublishAnUpdateOrderMessage()
{
var sender = new Sender();
var myBusMock = MockRepository.GenerateMock<IBus>();
sender.Bus = myBusMock;
sender.SendData(new OrderHeader());
myBusMock.AssertWasCalled(b => b.Publish<UpdateOrder>(Arg<UpdateOrder>.Is.Anything));
}
错误:
Rhino.Mocks.Exceptions.ExpectationViolationException
IBus.Publish<LVR.Communication.Bus.Order.Protocol.UpdateOrder>(anything); Expected #1, Actual #0.
[Fact]
public void SendData_PassingOrderHeader_PublishAnUpdateOrderMessage2()
{
var sender = new Sender();
var myBusMock = MockRepository.GenerateStub<IBus>();
sender.Bus = myBusMock;
bool iBusPublishHasBeenCalled = false;
myBusMock.Stub(b => b.Publish<UpdateOrder>(Arg<UpdateOrder>.Is.Anything)).WhenCalled(invocation =>
{
iBusPublishHasBeenCalled = true;
}
);
sender.SendData(new OrderHeader());
Assert.True(iBusPublishHasBeenCalled);
}
错误:
Assert.True() Failure
[Fact]
public void SendData_PassingOrderHeader_PublishAnUpdateOrderMessage3()
{
var sender = new Sender();
var myBusMock = MockRepository.GenerateMock<IBus>();
sender.Bus = myBusMock;
bool iBusPublishHasBeenCalled = false;
myBusMock.Expect(b => b.Publish<UpdateOrder>(Arg<UpdateOrder>.Is.Anything));
sender.SendData(new OrderHeader());
myBusMock.VerifyAllExpectations();
}
错误:
Rhino.Mocks.Exceptions.ExpectationViolationException
IBus.Publish<LVR.Communication.Bus.Order.Protocol.UpdateOrder>(anything); Expected #1, Actual #0.
答案 0 :(得分:0)
您的Publish
方法将lambda(即Action
或Func
)作为参数,而不是UpdateOrder
。我刚刚实现了您的第一次尝试,在我更改Arg
参数后,正确反映了它的方法签名。
作为旁注:根据自定义,模拟应该被验证用于方法调用,存根不应该。 存根只是使测试编译并运行而不影响结果的东西。为了方便起见,IIRC在犀牛嘲笑他们(几乎?)同义词。这使得你的第一和第三种方法看起来是最好的。