如何验证我的 Func在测试方法中调用

发布于 2024-10-12 01:48:37 字数 623 浏览 2 评论 0原文

我的泛型类采用 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包装起来。在一个新接口中并创建一个方法来包装它的 Invoke 方法,然后使用 Moq 来模拟该接口。然而,它似乎没有效果。

我错过了什么吗?任何想法将不胜感激。

谢谢,

安东

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

农村范ル 2024-10-19 01:48:37

您可以创建一个带有副作用的简单假 Func 闭包并验证这些副作用。一个好的方法是递增局部变量,因为它还可以让您断言它没有被调用超过应有的次数。像这样的东西:

int counter = 0;
Func<T> f = () => { counter++; return fakeT; }
var objectToTest = new TypeToTest<T>(f);
objectToTest.Construct();
Assert.Equal(1, counter);

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:

int counter = 0;
Func<T> f = () => { counter++; return fakeT; }
var objectToTest = new TypeToTest<T>(f);
objectToTest.Construct();
Assert.Equal(1, counter);
番薯 2024-10-19 01:48:37

您可以将 Func 包装在设置局部变量的匿名方法中:

bool wasInvoked = false;
Func<T> testFunc = () => { var ret = funcToTest(); wasInvoked = true; return ret; }

// Test something with testFunc instead of funcToTest
...

Assert.IsTrue(wasInvoked);

You can wrap the Func<T> in an anonymous method that sets a local variable:

bool wasInvoked = false;
Func<T> testFunc = () => { var ret = funcToTest(); wasInvoked = true; return ret; }

// Test something with testFunc instead of funcToTest
...

Assert.IsTrue(wasInvoked);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文