Mock a constructor with MOQ

浪尽此生 提交于 2019-12-23 08:03:06

问题


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!


回答1:


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);


来源:https://stackoverflow.com/questions/15420618/mock-a-constructor-with-moq

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