Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking objects without no-argument constructor in C# / .NET

Is it possible to create a mock from a class that doesn't provide a no-argument constructor and don't pass any arguments to the constructor? Maybe with creating IL dynamically?

The background is that I don't want to define interfaces only for testing. The workaround would be to provide a no-argument constructor for testing.

like image 543
deamon Avatar asked Mar 10 '11 16:03

deamon


1 Answers

Sure thing. In this example i'll use Moq, a really awesome mocking library.

Example:

public class MyObject {      public MyObject(object A, object B, object C)      {           // Assign your dependencies to whatever      } }  Mock<MyObject> mockObject = new Mock<MyObject>(); Mock<MyObject> mockObject = new Mock<MyObject>(null, null, null); // Pass Nulls to specific constructor arguments, or 0 if int, etc 

In many cases though, I assign Mock objects as the arguments so I can test the dependencies:

Mock<Something> x = new Mock<Something>(); MyObject mockObject = new MyObject(x.Object);  x.Setup(d => d.DoSomething()).Returns(new SomethingElse());  etc 
like image 161
Tejs Avatar answered Oct 09 '22 09:10

Tejs