2011-10-01 34 views
0

我是新來的c#以及Moq框架。我使用VS 2010 Express和NUnit的Moq for c#training不適用於套件中的第一個測試

在我的[設置]功能,我有:

this.mockAllianceController = new Mock<AllianceController>(); 
    this.mockAllianceController.Setup(ac => ac.getAllies(this.currentRealm)).Returns(new List<string>()); 

    ... 

    this.testObj = new DiplomacyLogic(this.mockAllianceController.Object); 

套件中的第一個測試得到空返回,而之後的每次測試得到空列表。我錯過了什麼?

更新:被測

代碼:

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將同時BTEST經過精細拋出NullReferenceException異常。任何幫助?

+0

發佈第一次測試的代碼。 –

+0

我是一個doofus。安裝程序後,我初始化this.currentRealm。 XD 所以真正的問題不是爲什麼第一次測試失敗,但爲什麼第二次測試通過?我猜沒有[TearDown],this.currentRealm沒有被​​破壞? – Shane

回答

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()

+0

currentRealm只是一個字符串。 我希望函數在使用除我在測試用例中指定的字符串以外的任何東西進行調用時返回null。 – Shane

+1

@Shane - Wimmel在正確的軌道上。在你的情況下,我會傳遞一個常量給安裝程序中的getAllies方法。這樣,初始化currentRealm時無關緊要。是的,你可以在測試方法之間共享狀態(壞)。重新初始化安裝程序中的所有內容,重置TearDown中的任何字段/全局變量,或者僅在測試方法中使用局部變量(可能使用測試工廠方法創建)。 – TrueWill

+0

參見http://stackoverflow.com/questions/6905406/does-nunit-create-a-new-instance-of-the-test-fixture-class-for-each-contained-tes – TrueWill

0

如果AllianceController是一類,而不是一個接口,你可以想做的事:

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

這意味着你創建一個模擬對象,將包裝已有的對象,並映射所有方法調用原始對象在默認情況下(除非明確Setup被調用)

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

0

我覺得你的設置以錯誤的順序完成,這將導致安裝不被第一次測試有效運行,然後在第二臺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; 
} 

我也覺得安裝程序代碼應該在設置的TestMethod的insteed,這是具有因你可能會寫會莫比不使用相同的設置僅針對該方法的其他測試。

相關問題