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 thin开发者_JS百科k 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
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);
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);
精彩评论