在 Moq 中调用回调
我有一个执行异步服务调用的方法。我通过传入回调来调用这个类。
public void GetRights(EventHandler<GetRightsCompletedEventArgs> callback)
{
ServiceClient client = new ServiceClient();
client.GetRightsCompleted += new EventHandler<GetRightsCompletedEventArgs>(callback);
client.GetRightsAsync();
}
GetRights(GetRightsCallback);
我正在使用 MSTest 创建测试,并且在 Moq 中模拟了包含类 (IGetRightsProxy)。测试中调用该方法时如何调用回调?
GetRightsForCurrentUserCompletedEventArgs results =
new GetRightsCompletedEventArgs(
new object[] { new ObservableCollection<Right>()}, null, false, null);
Mock<IGetRightsProxy> MockIGetRightsProxy = new Mock<GetRightsProxy>();
I have a method that performs an asynchronous service call. I call this class by passing in the callback.
public void GetRights(EventHandler<GetRightsCompletedEventArgs> callback)
{
ServiceClient client = new ServiceClient();
client.GetRightsCompleted += new EventHandler<GetRightsCompletedEventArgs>(callback);
client.GetRightsAsync();
}
GetRights(GetRightsCallback);
I'm creating tests with MSTest, and I've mocked the containing class (IGetRightsProxy) in Moq. How can I invoke the callback when this method is called in the test?
GetRightsForCurrentUserCompletedEventArgs results =
new GetRightsCompletedEventArgs(
new object[] { new ObservableCollection<Right>()}, null, false, null);
Mock<IGetRightsProxy> MockIGetRightsProxy = new Mock<GetRightsProxy>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
做我想做的事情的一种方法是像这样扩展类:
我一直在寻找在 Moq 中调用回调的方法,但这也有效。
One way of doing what I want is to extend the class like this:
I was looking for ways to invoke the callback in Moq, but this works, too.
您想在您的模拟中查看 Moq 的
Callback()
扩展;当测试代码在
IGetRightsProxy
模拟上调用GetRights()
时,它传入的实际EventHandler
随后将被传递到 Moq 的 < code>Callback() 方法。注意:类型推断适用于应用于 Callback() 的泛型,但我发现在这些情况下,显式定义传递到方法中的类型更具可读性。
You want to be looking at Moq's
Callback()
extension on your mock;When the code under test calls
GetRights()
on theIGetRightsProxy
mock the actualEventHandler<GetRightsCompletedEventArgs>
it passes in will subsequently be passed into Moq'sCallback()
method.Note: Type inference will work on the generic applied to
Callback()
but I find in these cases it is a bit more readable to explicitly define the type being passed into the method.