我在单元测试中具有以下代码
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内部的第三阶段?理想情况下是:
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()
是不可测试的,因为您创建了真实服务的新实例,并且无法模拟它。
如果要模拟它,则必须在依赖项注入中注入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容器。
感谢您的想法,伙计们。我最终制作了另一个版本的其他class.foo(),该版本在第三级实例中进行,并且在没有它的版本中创建了一个实例。测试时,我可以致电FOO(模拟),但是用户可以使用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);
}