模拟的类在单元测试
问题描述:
我有一个单元测试模拟的类在单元测试
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();
}
}
三级栏目仍处于开发阶段,但我想一个类能够使用moq运行我的单元测试。有没有办法告诉moq模拟TestClass中的ThirdClass而不使用其他类使用/取决于moq?理想的情况是这样的:
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();
}
答
方法foo()
在OtherClass
类不是单元测试,因为你创造实实在在的服务的新实例,你不能嘲笑它。
如果你想嘲笑它,那么你必须注入依赖注入ThirdClass
。
的OtherClass
例子是:
public class OtherClass
{
private readonly ThirdClass _thirdClass;
public OtherClass(ThirdClass thirdClass)
{
_thirdClass = thirdClass;
}
public void foo()
{
_thirdClass.bar();
}
}
您的测试方法与测试例如其他类可以是:
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容器。
答
感谢您的想法,伙计。我最终创建了另一个接受ThirdClass实例的OtherClass.foo()版本,并且在没有它的版本中创建了一个实例。测试时,我可以调用foo(mockThird),但用户可以使用foo()。
using ThirdClass;
public class OtherClass
{
public void foo(ThirdClass third)
{
third.bar();
}
public void foo()
{
foo(new ThirdClass());
}
}
在测试类
public void TestMethod()
{
Mock<ThirdClass> third = new Mock<ThirdClass>();
third.setup(o => o.bar()).Returns(/*mock implementation*/);
OtherClass testObject= new OtherClass();
testObject.foo(third);
}
+0
我只是想让你知道,根据这个门户的规定,你不能发布其他问题作为答案。如有必要,您必须编辑您的原始问题或添加为注释。如果您在编辑问题,请确保与答案保持一致。谢谢 – kat1330
听起来像'OtherClass'应* *提供的实例'ThirdClass'代替*创建*之一。 – David