如何验证我的 Func在测试方法中调用
我的泛型类采用 Func
我使用 Moq,在我的测试代码中是这样的:
[Fact]
public void Construct_EnsureInvokeFunction()
{
_objectToTest=new TypeToTest<T>(It.IsAny<Func<T>>());
_objectToTest.Construct();
//here I want to ensure that the passed parameter is invoked
//however since I can't mock Func<T>, I dont know how to verify
//whether Invoke method of Func<T> is triggered
}
我能想到的一种解决方法是将我的 Func
我错过了什么吗?任何想法将不胜感激。
谢谢,
安东
My generic class takes a Func<T> parameter in constructor, and I want to test one of its methods which basically invoke the constructor parameter.
I use Moq and in my test code is something like this:
[Fact]
public void Construct_EnsureInvokeFunction()
{
_objectToTest=new TypeToTest<T>(It.IsAny<Func<T>>());
_objectToTest.Construct();
//here I want to ensure that the passed parameter is invoked
//however since I can't mock Func<T>, I dont know how to verify
//whether Invoke method of Func<T> is triggered
}
One workaround that I can think is to wrap my Func<T> inside a new interface and create a method to wrap it's Invoke method, and then use Moq to mock the interface. However it doesn't seem effective.
Am I missing something? Any idea will be appreciated.
Thanks,
Anton
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建一个带有副作用的简单假
Func
闭包并验证这些副作用。一个好的方法是递增局部变量,因为它还可以让您断言它没有被调用超过应有的次数。像这样的东西:You can create a simple fake
Func<T>
closure with side-effects and verify those side-effects. A good one is incrementing a local variable because it also lets you assert that it was not called more than it should. Something like this:您可以将
Func
包装在设置局部变量的匿名方法中:You can wrap the
Func<T>
in an anonymous method that sets a local variable: