C# – Moq cannot create mock object of class with nullable parameter in the constructor

cmockingmoqnullableunit testing

I have this class:

public class TestClass
{
 public TestClass(int? foo, string bar)
 {
   //..Something
 }
}

I am trying to mock it using MOQ like this

var mockA = new Mock<A>(new object[] {(int?)1, string.Empty})

or this,

var mockA = new Mock<A>(new object[] {1 as int?, string.Empty})

even this

var mockA = new Mock<A>(new object[] {(int?)null, string.Empty})

When I try to get the object like this

var objA = mockA.Object

it throws this exception

Can not instantiate proxy of class: TestClass.
Could not find a constructor that would match given arguments:
System.Int32,
System.String

(for the third one it throws null reference exception)

How to make it recognize that first argument is of type Nullable System.Int32 and not System.Int32.

(Please ignore that I am mocking a class and not an interface.)

Best Answer

In order to Mock an object with Moq, the object itself must have a public empty constructor. Methods you want to mock must be virtual in order to be overridden.

Edit:

I'm running Moq v4.0.20926 (latest from NuGet) and the following work:

[TestMethod]
public void TestMethod1()
{
    var mock = new Mock<TestClass>(new object[] {null, null});
    mock.Setup(m => m.MockThis()).Returns("foo");

    Assert.AreEqual("foo", mock.Object.MockThis());
}

public class TestClass
{
    public TestClass(int? foo, string bar)
    {
    }

    public virtual string MockThis()
    {
        return "bar";
    }
}