在过去的几年里,我一直在使用Moq来满足我的模拟需求,但是在查看了FakeItEasy之后,我想试一试。
我经常想测试是否使用正确的参数调用了一个方法,但我发现使用 FakeItEasy 没有令人满意的方法。
我有以下代码要测试:
public class WizardStateEngine : IWizardStateEngine
{
private readonly IWorkflowInvoker _workflowInvoker;
private List<CustomBookmark> _history;
public WizardStateEngine(IWorkflowInvoker workflowInvoker)
{
_workflowInvoker = workflowInvoker;
}
public void Initialize(List<CustomBookmark> history)
{
_history = history;
}
public WizardStateContext Execute(Command command, WizardStateContext stateContext, CustomBookmark step)
{
Activity workflow = new MyActivity();
var input = new Dictionary<string, object>();
input["Action"] = command;
input["Context"] = stateContext;
input["BookmarkHistory"] = _history;
var output = _workflowInvoker.Invoke(workflow, input);
_history = output["BookmarkHistory"] as List<CustomBookmark>;
return output["Context"] as WizardStateContext;
}
public List<CustomBookmark> GetBookmarkHistory()
{
return _history;
}
}
我想编写一些测试来验证 _workflowInvoker.Invoke() 的输入。我的 TestInitialize 方法设置所需的资源并将输入字典作为本地字段 _wfInput 保存到 _workflowInvoker.Invoke()。
[TestInitialize]
public void TestInitialize()
{
_wizardStateContext = new WizardStateContext();
_workflowInvoker = A.Fake<IWorkflowInvoker>();
_wizardStateEngine = new WizardStateEngine(_workflowInvoker);
_outputContext = new WizardStateContext();
_outputHistory = new List<CustomBookmark>();
_wfOutput = new Dictionary<string, object>
{{"Context", _outputContext}, {"BookmarkHistory", _outputHistory}};
_history = new List<CustomBookmark>();
A.CallTo(() =>
_workflowInvoker.Invoke(A<Activity>.Ignored, A<Dictionary<string, object>>.Ignored))
.Invokes(x => _wfInput = x.Arguments.Get<Dictionary<string, object>>("input"))
.Returns(_wfOutput);
_wizardStateEngine.Initialize(_history);
}
设置后,我有多个这样的测试:
[TestMethod]
public void Should_invoke_with_correct_command()
{
_wizardStateEngine.Execute(Command.Start, null, null);
((Command) _wfInput["Action"]).ShouldEqual(Command.Start);
}
[TestMethod]
public void Should_invoke_with_correct_context()
{
_wizardStateEngine.Execute(Command.Start, _wizardStateContext, null);
((WizardStateContext) _wfInput["Context"]).ShouldEqual(_wizardStateContext);
}
[TestMethod]
public void Should_invoke_with_correct_history()
{
_wizardStateEngine.Execute(Command.Start, _wizardStateContext, null);
((List<CustomBookmark>) _wfInput["BookmarkHistory"]).ShouldEqual(_history);
}
我不喜欢 TestInitialize 中的魔术字符串“输入”来获取传递的参数(或幻数)。我可以在没有本地字段的情况下编写测试,如下所示:
[TestMethod]
public void Should_invoke_with_correct_context()
{
_wizardStateEngine.Execute(Command.Start, _wizardStateContext, null);
A.CallTo(() =>
_workflowInvoker.Invoke(A<Activity>._,
A<Dictionary<string, object>>.That.Matches(
x => (WizardStateContext) x["Context"] == _wizardStateContext)))
.MustHaveHappened();
}
但我发现本地字段的测试更具可读性。
有什么方法可以将输入保存为我的测试类中的字段,而不需要幻数或字符串?
我希望问题中的更新示例能说明我为什么要使用本地字段。如果我能找到一种可读的好方法,我非常愿意在没有本地字段的情况下编写测试。