用Moq测试接受委托的方法 [英] Testing a method accepting a delegate with Moq
问题描述
我的代码使用的组件实现了这样的接口
my code is using a component implementing an interface like this
public interface IFoo
{
void DoSomething(string p1);
void DoSomething(string p1, Action<string> p2);
}
到目前为止,我正在使用第一种方法,但是我打算移至第二种方法,并且我希望将覆盖率保持在尽可能高的水平.
As of this moment, I'm using the first method, but I plan to move to the second one and I want to keep my coverage as high as possible.
只是我真的不知道如何检查委托,甚至不设置Moq来模拟界面.
Just that I really don't know how to inspect the delegate or even just setup Moq to mock the interface.
我尝试过
mock.Setup(p => p.DoSomething(It.IsAny<string>(), It.IsAny<Delegate>()));
mock.Setup(p => p.DoSomething(It.IsAny<string>(), It.IsAny<Action<string>>()));
但任何一个都不会让我建立.有什么建议吗?
but neither will let me build. Any suggestion?
推荐答案
该行:
mock.Setup(p => p.DoSomething(It.IsAny<string>(), It.IsAny<Delegate>()));
必须不进行编译,因为DoSomething
需要Action<string>
,并且Delegate
不能隐式转换为Action<string>
.您的另一行:
must not compile becaue DoSomething
requires an Action<string>
, and Delegate
is not implicitly convertible to Action<string>
. Your other line:
mock.Setup(p => p.DoSomething(It.IsAny<string>(), It.IsAny<Action<string>>()));
有效且正确!
仅当p2
满足某些条件时才能设置,例如:
You can setup only when p2
satisfies some criterion, for example:
mock.Setup(p => p.DoSomething(It.IsAny<string>(),
It.Is((Action<string> p2) => p2 != null && p2.Target is SomeClass)
));
或者您可以使用CallBack
进行检查:
Or you can use CallBack
to check things:
mock.Setup(p => p.DoSomething(It.IsAny<string>(), It.IsAny<Action<string>>()))
.CallBack((string p1, Action<string> p2) =>
{
// your code (for example Asserts) here,
// use p2
});
当然,您可以检查Action<string>
的数量是有限制的,但是您可以查看它是否为非空值,查看其p2.Target
是否为非空值或具有特定类型或等于给定实例,则可以查看p2.Method
是否是已知(命名)方法,或者如果期望有所谓的多播委托,则可以使用p2.GetInvocationList()
.
Of course, there is a limit to how much you can inspect an Action<string>
, but you can see if it is non-null, see if its p2.Target
is non-null or has a specific type or equals a given instance, you can see if p2.Method
is a known (named) method, or you could use p2.GetInvocationList()
if you expect a so-called multicast delegate.
这篇关于用Moq测试接受委托的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!