I'd like to be able to test a class initialises correctly using Moq:
class ClassToTest
{
public ClassToTest()
{
Method1(@"C:\myfile.dat")
}
public virtual void Method1(string filename)
{
// mock this method
File.Create(filename);
}
}
I thought I'd be able to use the CallBase
property to create a testable version of the class, then use .Setup()
to ensure Method1()
does not execute any code.
However, creating the Mock<ClassToTest>()
doesn't call the constructor, and if it did it'd be too late to do the Setup()
!
If this is impossible, what is the best way round the problem whilst ensuring that the constructor behaves correctly?
EDIT: To make it clearer, I've added a parameter to Method1()
to take a filename and added some behaviour. The test I'd like to write would be a working version on the following:
[Test]
public void ClassToTest_ShouldCreateFileOnInitialisation()
{
Mock<ClassToTest> mockClass = new Mock<ClassToTest>() { CallBase = true };
mockClass.Setup(x => x.Method1(It.IsAny<string>());
mockClass.Verify(x => x.Method1(@"C:\myfile.dat"));
}