Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a constructor with MOQ

Tags:

c#

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!

like image 470
Elisabeth Avatar asked Mar 14 '13 21:03

Elisabeth


People also ask

Can you mock a constructor?

0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes. Similar to mocking static method calls with Mockito, we can define the scope of when to return a mock from a Java constructor for a particular Java class.

What can be mocked with MOQ?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces.

Can we mock constructor C#?

It would be ideal if we could mock the actual dependent classes, but in C# we can only mock interfaces instead of classes. These interfaces are mocked up and the methods are set to return the required results to test the code. Mocked objects are then passed into the classes as dependencies (usually in the constructor).

How does MOQ mock work?

Mock objects allow you to mimic the behavior of classes and interfaces, letting the code in the test interact with them as if they were real. This isolates the code you're testing, ensuring that it works on its own and that no other code will make the tests fail.


1 Answers

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);
like image 198
nemesv Avatar answered Sep 20 '22 02:09

nemesv