Elisabeth
Elisabeth

Reputation: 21206

Mock a constructor with MOQ

I have a class B with a constructor parameter of Type class A.

I want that class A is mocked when I create a mock for class B.

How can I do this? I tried MockBehavior Loose/Strict but this did not help!

Upvotes: 9

Views: 16272

Answers (1)

nemesv
nemesv

Reputation: 139748

If you are mocking classes you can pass in the constructor arguments when calling new Mock<T>:

So if you have the classes:

public class A {}

public class B
{
    private readonly A a;

    public B(A a) { this.a = a; }
}

The following code creates a mock B with a mock A:

var mockA = new Mock<A>();
var mockB = new Mock<B>(mockA.Object);

Upvotes: 18

Related Questions