Moq and Constructors - Testing Initialization Behavior

I would like to check the class initialization 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 could use the CallBase property to create a test version of the class, and then use .Setup() to ensure that Method1() does not execute any code.

However, creating a Mock<ClassToTest>() does not call the constructor, and if that were done, it would be too late to do Setup() !

If this is not possible, is it best to solve the problem by ensuring that the constructor behaves correctly?

EDIT: To make it more understandable, I added the Method1() parameter to take the file name and added some kind of behavior. The test I would like to write will be a working version of the following content:

 [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")); } 
+4
source share
1 answer

Recession inside Moq.Mock (actually inside CastleProxyFactory , which uses Moq )

 mockClass.Object 

will call the constructor using Activator.CreateInstance()

So your test will 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")); } 
+9
source

All Articles