Search code examples
c#.net-coremoqxunit

Why does calling someMockInstance.Object call constructor?


Sorry if this is really obvious...

I'm trying to understand why calling someMockInstance.Object calls the class constructor.

Here's an example:

public class Foo
{
  public Foo()
  {
    // Init some stuff
  }
  
  public virtual string DoSomething()
  {
    // Blah
  }
}
public class BarTest
{
  [Fact]
  public void SomeMethod()
  {
    var mockFoo = new Mock<Foo>();
    mockFoo.Setup(m => m.DoSomething()).Returns("SomeValue");

    // This causes a call to `Foo.Foo()`
    var result = new Bar(mockFoo.Object).SomeMethod();

    result.Should().Be(true);
  }
}

And I guess as importantly, can we avoid it?

Thanks!


Solution

  • You're mocking a concrete class (rather than an interface). To do this, Moq will dynamically create a class which subclasses Foo.

    However, subclasses always need to call a constructor on their base class, and so this dynamically-created subclass will call Foo's parameterless constructor. This is a rule imposed by the .NET runtime which Moq cannot break.