我可以在Rhino Mocks中设置AssertWasCalled失败时显示的用户友好消息吗?

时间:2011-12-28 07:37:35

标签: c# .net unit-testing tdd rhino-mocks

我是否可以在模拟对象上编写以下断言,其显示“如果断言失败,则”UnBookFlight未使用适当的参数调用,甚至不调用“?

mockBookingService
              .AssertWasCalled(ms=>ms.UnBookFlight(Arg<DateTime>.Is.Equal(dummyDate)));

2 个答案:

答案 0 :(得分:3)

根据this article,您可以在传递给AssertWasCalled()的方法选项中指定一条消息:

mockBookingService.AssertWasCalled(
    ms => ms.UnBookFlight(Arg<DateTime>.Is.Equal(dummyDate)),
    options => {
        options.Message("UnBookFlight was not called with proper parameters or not even called");
    });

答案 1 :(得分:0)

据我所知,Rhino没有办法指定你自己的消息。

您可以编写自己的方法来捕获Rhino的ExpectationViolationException,然后打印出您想要的消息。

一个粗略的例子是:

public static class RhinoExtensions
{
    public static void AssertWasCalledWithMessage<T>(this T mock, Expression<Func<T, object>> action)
    {
        try
        {
            mock.AssertWasCalled(action.Compile());
        }
        catch (ExpectationViolationException)
        {
            Console.WriteLine(string.Format("{0} was not called with proper parameters or was not called.", (action.Body as MethodCallExpression).Method.Name));
            throw;
        }
    }
}

然后使用:

mockBookingService.AssertWasCalledWithMessage(ms=>ms.UnBookFlight(Arg<DateTime>.Is.Equal(dummyDate)));