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

微笑、不失礼 提交于 2020-01-03 06:44:11

问题


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.


回答1:


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



回答2:


It is wrong to believe that you are providing interfaces only for testing. Interfaces are there to provide abstractions and weaken the coupling between the different layers of your code making them more reusable in different contexts.

This being said the answer will depend on the mocking framework you are using. For example with Rhino Mocks you could have:

public class Foo
{
    public Foo(string bar)
    { }

    public virtual int SomeMethod()
    {
        return 5;
    }
}

and then:

var fooMock = MockRepository.GeneratePartialMock<Foo>("abc");
fooMock.Expect(x => x.SomeMethod()).Return(10);


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!