对于c#培训的Moq没有在套件中进行第一次测试

时间:2011-10-01 06:41:58

标签: c# moq

我也是c#和Moq框架的新手。我正在使用VS 2010 express和NUnit

在我的[设置]功能中,我有:

    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传递正常。有什么帮助吗?

3 个答案:

答案 0 :(得分:2)

如果您还显示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>());

请注意It.IsAny<string>()作为getAllies()的参数。

答案 1 :(得分:0)

如果AllianceController是一个类而不是一个接口,您可能希望这样做:

this.mockAllianceController = new Mock<AllianceController>();
this.mockAllianceController.CallBase = True

这意味着您创建了一个Mock对象,该对象将包装现有对象并默认将所有方法调用映射到原始对象(除非已调用显式Setup

(见http://code.google.com/p/moq/wiki/QuickStart#Customizing_Mock_Behavior

答案 2 :(得分:0)

我认为你的设置是以错误的顺序完成的,这导致设置在第一个testrun中无效,然后在第二个testrun中已经创建this.testObj = new DiplomacyLogic(this.mockAllianceController.Object);并初始化设置。这意味着您应该在设置之前初始化DiplomacyLogic以获得所需的结果。

我还包含了一个拆解代码,因此您可以为每个测试获得新鲜的对象,这是一个很好的做法,因此测试不依赖于彼此。

尝试以下代码。

[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;
}

我还认为设置代码应该在设置的测试方法中,并且因为您可能会编写其他测试,因为maby不会对该方法使用相同的设置。

相关问题