未调用如何使用FakeIseasy来断言方法
本文关键字:断言 方法 FakeIseasy 何使用 调用 | 更新日期: 2023-09-27 18:25:29
我想断言没有发送任何东西,也就是说_dispatcher.Dispatch
没有被调用。
interface
被伪造/嘲笑:
interface IDispatcher
{
void Dispatch<T>(T command,
Stuff stuff = null,
TimeSpan? timeout = null,
int? retries = null) where T : Command;
}
在测试体中:
_dispatcher = A.Fake<IDispatcher>();
// do stuff
A.CallTo(() => _dispatcher.Dispatch(A<Command>.Ignored,
A<Stuff>.Ignored,
A<TimeSpan?>.Ignored,
A<int?>.Ignored)).MustNotHaveHappened();
当发送了东西时,此测试通过。
有什么想法吗?我是否错误地使用了FakeIseasy?
@Scoobie
您用来调用分派方法的实际类型真的是Command
吗?或者它是派生类型?如果它是一个可能导致您观察到的行为的派生类型。
请参见以下示例:var dispatcher=A.Fake();
dispatcher.Dispatch(new Command(), new Stuff());
A.CallTo(() => dispatcher.Dispatch(A<Command>.Ignored,
A<Stuff>.Ignored,
A<TimeSpan?>.Ignored,
A<int?>.Ignored)).MustNotHaveHappened();
正如预期的那样,此测试将失败。
但如果你有这样的东西:
public class NewCommand : Command
{
}
以下测试
var dispatcher = A.Fake<IDispatcher>();
dispatcher.Dispatch(new NewCommand(), new Stuff());
A.CallTo(() => dispatcher.Dispatch(A<Command>.Ignored,
A<Stuff>.Ignored,
A<TimeSpan?>.Ignored,
A<int?>.Ignored)).MustNotHaveHappened();
会成功的,尽管你预料会失败。
但这就是FakeIseasy的工作原理。如果你想讨论它是否应该以这种方式工作,请前往https://github.com/FakeItEasy/FakeItEasy请打开一期。
现在是你的问题。我假设您希望确保IDispatcher.Dispatch
方法永远不会被调用,无论泛型参数具有哪种类型。你有几个选择:
由于Dispatch
方法是IDispatcher
上唯一的方法,我只想写下面的
A.CallTo(dispatcher).MustNotHaveHappened();
当调用dispatcher
实例上的任何方法(或属性)时,此操作将失败。
A.CallTo(dispatcher).Where(_ => _.Method.Name == "Dispatch")
.MustNotHaveHappened();
只有当调用Dispatch
时,这才会失败,尽管这种用法是重构的杀手。
如果可能的话,我更喜欢你的第一种选择。