views:

58

answers:

1

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"));
}
+1  A: 

Way down inside of Moq.Mock (actually inside the CastleProxyFactory that Moq uses)

mockClass.Object

will call the constructor by way of Activator.CreateInstance()

So your test would look something like

[Test]
public void ClassToTest_ShouldCreateFileOnInitialisation()
{
    Mock<ClassToTest> mockClass = new Mock<ClassToTest>();
    mockClass.Setup(x => x.Method1(It.IsAny<string>());

    var o = mockClass.Object;

    mockClass.Verify(x => x.Method1(@"C:\myfile.dat"));
}
arootbeer