c#培训的最低要求,不能在套件中进行第一次测试
本文关键字:套件 测试 第一次 不能 培训 | 更新日期: 2023-09-27 18:10:15
我也是c#和Moq框架的新手。我使用vs2010 express和NUnit
在我的[Setup]函数中,我有:
this.mockAllianceController = new Mock<AllianceController>();
this.mockAllianceController.Setup(ac => ac.getAllies(this.currentRealm)).Returns(new List<string>());
...
this.testObj = new DiplomacyLogic(this.mockAllianceController.Object);
套件中的第一个测试返回null,之后的每个测试返回空列表。我错过了什么?
更新:
待测代码:
public void ApplyRelations() {
List<string> allies = this.AllianceController.getAllies(this.RealmName);
foreach (string ally in allies) {
...
}
}
public virtual List<string> getAllies(string realm) {
...
}
两个测试用例:
[Test]
public void aTest() {
this.testObj.ApplyRelations();
}
[Test]
public void bTest() {
this.testObj.ApplyRelations();
}
aTest将抛出NullReferenceException,而bTest通过正常。任何帮助吗?
如果您还显示getAllies
的声明和this.currentRealm
是什么,将会有所帮助。
但是你可能想改变这一行:
this.mockAllianceController.Setup(ac => ac.getAllies(this.currentRealm)).Returns(new List<string>());
这:
this.mockAllianceController.Setup(ac => ac.getAllies(It.IsAny<string>())).Returns(new List<string>());
注意getAllies()
参数为It.IsAny<string>()
如果AllianceController
是一个类而不是一个接口,您可能想要这样做:
this.mockAllianceController = new Mock<AllianceController>();
this.mockAllianceController.CallBase = True
这意味着您创建一个Mock对象,该对象将包装现有对象,并在默认情况下将所有方法调用映射到原始对象(除非已调用显式Setup
)
(见http://code.google.com/p/moq/wiki/QuickStart Customizing_Mock_Behavior)
我认为您的设置是以错误的顺序完成的,这导致设置在第一次测试中无效,然后在第二次测试中已经创建了this.testObj = new DiplomacyLogic(this.mockAllianceController.Object);
并初始化了设置。这意味着您应该在设置之前初始化DiplomacyLogic
以获得所需的结果。
我还包含了一个teardown代码,这样您就可以为每个测试获得新的对象,这是一个很好的实践,这样测试就不会相互依赖了。
试试下面的代码。
[Setup]
public void Setup()
{
this.mockAllianceController = new Mock<AllianceController>();
this.testObj = new DiplomacyLogic(this.mockAllianceController.Object);
this.mockAllianceController.Setup(ac => ac.getAllies(this.currentRealm)).Returns(new List<string>());
}
[TearDown]
public void TearDown()
{
this.mockAllianceController = null;
this.testObj = null;
}
我还认为设置代码应该在testmethod中而不是setup中,这是因为您可能编写的其他测试可能不会为该方法使用相同的设置