编写TDD(测试驱动开发)编程时遇到问题。让我们说,我创建了简单的测试方法:
public class UtilsTest {
private IUtilsService _utilService = new UtilService();
[Fact]
public void OneUtilTest {
//here is test code
}
}
它运作良好。编写测试后,我想向UtilService添加任何逻辑。例如:
public class UtilService : IUtilService {
public string UtilLogicOne(object param) {
//util one logic...
}
}
好的,但写作时我需要注入一个或多个依赖项。例如:
public class UtilService : IUtilService {
public UtilService(IDepsOne depsOne, IDepsTwo depsTwo) {
this.DepsOne = depsOne;
//etc...
}
public string UtilLogicOne(object param) {
var result = this.DepsOne.GetResult();
//util one logic...
}
}
这个使用的依赖项当然拥有下一个注入的依赖项,如数据适配器和其他。现在我需要在Test中修复没有参数化构造函数,因为在第一步中我没有参数化构造函数。
如何使用注入的依赖项立即使用服务?
private IUtilsService _utilService = new UtilService(); //instead the single instance I need to get service with injected dependencies.
有可能吗?非常感谢你的时间。
答案 0 :(得分:3)
我建议调查Moq nuget包来处理你注入的依赖项。有一篇很好的文章here讨论了如何在TDD中使用Moq。
所以你可能想要这样的东西:
var depsOneMock = new Mock<IDepsOne>();
var depsTwoMock = new Mock<IDepsTwo>();
// Call .Setup() on your mocks here if you want to mock property values or functions
var utilService = new UtilService(depsOne.Object, depsTwo.Object);
// Continue with your test