[英]Is it possible to pass a Moq object to a C# class constructor?
I have MyClass class that receives an instance of TheirClass in the constructor. 我有MyClass类,该类在构造函数中接收theirClass的实例。 MyClass uses a property value of the instance in MyMethod function, something like this
MyClass在MyMethod函数中使用实例的属性值,类似这样
public class MyClass
{
ITheirClass theirClass;
public MyClass( ITheirClass TheirClass)
{
theirClass =TheirClass;
}
public MyMethod ()
{
if (theirClass.TheirProperty) return;
}
}
I would like to create a unit test for MyClass and MyClass.MyMethod function. 我想为MyClass和MyClass.MyMethod函数创建一个单元测试。 I created a Moq object like this
我这样创建了一个Moq对象
var MoqTheirClass = new Mock<ITheirClass>();
MoqTheirClass.SetupGet(p => p.TheirProperty).Returns(false);
But, MoqTheirClass object is not convertible to ITheirClass type and I cannot pass it to the MyClass constructor. 但是,MoqTheirClass对象不能转换为ITheirClass类型,并且我无法将其传递给MyClass构造函数。
The question is how can I create a Moq TheirClass object with the preset TheirClass.TheirProperty value and pass it to MyClass constructor? 问题是如何使用预设的themClass.TheirProperty值创建Moq他们的类对象并将其传递给MyClass构造函数?
Is there any other way to unit test MyClass.MyMethod function? 还有其他方法可以对MyClass.MyMethod函数进行单元测试吗?
您需要像这样从MoqTheirClass
对象传递Object
属性:
MyClass myClass = new MyClass(MoqTheirClass.Object);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.