我应该如何嘲笑下面的行?
ABCRepository abcObj = new ABCRepository();
var model = new NamesList
{
ALayoutNames = abcObj.ALayout(),
BLayoutNames = abcObj.BLayout(),
CLayoutNames = abcObj.CLayout(),
DLayoutNames = abcObj.DLayout(),
ELayoutNames = abcObj.ELayout()
};
我用下面的界面嘲笑了第一行
Mock<IABCRepository> _iabcrepository = new Mock<IABCRepository>();
但是如何继续处理NamesList对象?
这需要一些重构。这就是为什么我发现单元测试有助于创建更好的代码的原因。
因此,逐步进行:
public class ClassToTest {
private IABCRepository abcObj;
public ClassToTest(IABCRepository repo) {
this.abcObj = repo;
}
public DoingSomething() {
var model = new NamesList
{
ALayoutNames = this.abcObj.ALayout(),
BLayoutNames = this.abcObj.BLayout(),
CLayoutNames = this.abcObj.CLayout(),
DLayoutNames = this.abcObj.DLayout(),
ELayoutNames = this.abcObj.ELayout()
};
}
}
Mock<IABCRepository> _iabcrepository = new Mock<IABCRepository>();
_iabcrepository.Setup(foo => foo.ALayout()).Returns(MockValue);
_iabcrepository.Setup(foo => foo.BLayout()).Returns(MockValue);
// etc
var classToTest = new ClassToTest(_iabcrepository.Object);
现在,当您调用DoSomething函数时,模拟的存储库将返回模拟的值。