在单元测试中模拟类中的类 [英] Mock a Class in a Class in a Unit Test
问题描述
我在单元测试中有以下代码
I have the following code in a unit test
using Moq;
using OtherClass;
[TestClass]
public class TestClass
{
[TestMethod]
public void TestMethod()
{
OtherClass other = new OtherClass();
OtherClass.foo();
}
}
这里是另一个类
using ThirdClass;
public class OtherClass
{
public void foo()
{
ThirdClass third = new ThirdClass();
third.bar();
}
}
ThirdClass 仍在开发中,但我希望能够使用 moq 运行我的单元测试.有没有办法告诉 moq 在 TestClass 内模拟 ThirdClass 而没有 OtherClass 使用/依赖 moq?理想情况下是这样的:
ThirdClass is still under development, but I want to be able to run my unit tests using moq. Is there a way to tell moq to mock ThirdClass inside TestClass without having OtherClass use/depend on moq? Ideally something like:
public void TestMethod()
{
OtherClass other = new OtherClass();
Mock<ThirdClass> third = new Mock<ThirdClass>();
third.setup(o => o.bar()).Returns(/*mock implementation*/);
/*use third in all instances of ThirdClass in OtherClass*/
OtherClass.foo();
}
推荐答案
OtherClass
类中的方法 foo()
不可单元测试,因为您创建了真实服务的新实例你不能嘲笑它.
Method foo()
in class OtherClass
is not unit testable because you creating new instance of real service and you cannot mock it.
如果你想模拟它,那么你必须使用依赖注入注入 ThirdClass
.
If you want to mock it then you have to inject ThirdClass
with dependency injection.
OtherClass
的例子是:
public class OtherClass
{
private readonly ThirdClass _thirdClass;
public OtherClass(ThirdClass thirdClass)
{
_thirdClass = thirdClass;
}
public void foo()
{
_thirdClass.bar();
}
}
您的测试方法与测试其他类的示例可以是:
Your test method with example of testing other class can be:
public void TestMethod()
{
// Arrange
Mock<ThirdClass> third = new Mock<ThirdClass>();
third.setup(o => o.bar()).Returns(/*mock implementation*/);
OtherClass testObject= new OtherClass(third);
// Action
testObject.foo();
// Assert
///TODO: Add some assertion.
}
您可以使用 Unity DI 容器.
You can use example try with Unity DI container.
这篇关于在单元测试中模拟类中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!