用最小起订量模拟构造函数 [英] Mock a constructor with MOQ

查看:79
本文介绍了用最小起订量模拟构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个B类,其构造函数参数为Type类A.

I have a class B with a constructor parameter of Type class A.

我希望在为类B创建模拟时模拟A类.

I want that class A is mocked when I create a mock for class B.

我该怎么做?我尝试过MockBehavior Loose/Strict,但这没有帮助!

How can I do this? I tried MockBehavior Loose/Strict but this did not help!

推荐答案

如果要模拟类,则可以在调用new Mock<T>时传入构造函数参数:

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

以下代码使用模拟A创建模拟B:

The following code creates a mock B with a mock A:

var mockA = new Mock<A>();
var mockB = new Mock<B>(mockA.Object);

这篇关于用最小起订量模拟构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆