如何断言一个动作被称为 [英] How to assert that an action was called
问题描述
我需要的资产由模拟组件调用的操作。
I need to asset an action called by a mock component.
public interface IDispatcher
{
void Invoke(Action action);
}
public interface IDialogService
{
void Prompt(string message);
}
public class MyClass
{
private readonly IDispatcher dispatcher;
private readonly IDialogservice dialogService;
public MyClass(IDispatcher dispatcher, IDialogService dialogService)
{
this.dispatcher = dispatcher;
this.dialogService = dialogService;
}
public void PromptOnUiThread(string message)
{
dispatcher.Invoke(()=>dialogService.Prompt(message));
}
}
..and in my test..
[TestFixture]
public class Test
{
private IDispatcher mockDispatcher;
private IDialogService mockDialogService;
[Setup]
public void Setup()
{
mockDispatcher = MockRepository.GenerateMock<IDispatcher>();
mockDialogService = MockRepository.GenerateMock<IDialogService>();
}
[Test]
public void Mytest()
{
var sut = CreateSut();
sut.Prompt("message");
//Need to assert that mockdispatcher.Invoke was called
//Need to assert that mockDialogService.Prompt("message") was called.
}
public MyClass CreateSut()
{
return new MyClass(mockDipatcher,mockDialogService);
}
}
也许我需要重组的代码,但困惑于那。 ?能否请您指教。
Maybe I need to restructure the code, but confused on that. Could you please advise?
推荐答案
您的实际测试这行代码:
You are actually testing this line of code:
dispatcher.Invoke(() => dialogService.Prompt(message));
您类调用模拟调用另一个模拟的方法。这通常是简单的,你只需要确保调用时调用正确的参数。不幸的是,该参数是一个lambda并没有那么容易评估。但幸运的是,这是这使得它再次轻松模拟的呼叫:只需要调用它,并确认其他模拟了所谓的:
Your class calls the mock to invoke a method on another mock. This is normally simple, you just need to make sure that Invoke is called with the correct arguments. Unfortunately, the argument is a lambda and not so easy to evaluate. But fortunately, it is a call to the mock which makes it easy again: just call it and verify that the other mock had been called:
Action givenAction = null;
mockDipatcher
.AssertWasCalled(x => x.Invoke(Arg<Action>.Is.Anything))
// get the argument passed. There are other solutions to achive the same
.WhenCalled(call => givenAction = (Action)call.Arguments[0]);
// evaluate if the given action is a call to the mocked DialogService
// by calling it and verify that the mock had been called:
givenAction.Invoke();
mockDialogService.AssertWasCalled(x => x.Prompt(message));
这篇关于如何断言一个动作被称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!