Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/5262881/mocking-objects-without-no-argument-constructor-in-c-sharp-net

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...