2013-07-22 18 views
1

我正在嘗試編寫一個單元測試來測試一個基本上接受某些數據組的方法,然後運行一個方法。出於某種原因,我的設置從不被調用。我已經調試過,並且檢查了傳入和傳出的類型以及數據,並且在分組後它完全相同。任何想法爲什麼這不起作用?從未調用過的單元測試設置

這是在我的測試:

MyArray[] grouped = myArray 
        .SelectMany(x => x.AccountValues) 
        .GroupBy(x => x.TimeStamp) 
        .Select(g2 => 
         new AccountValue { 
           Amount = g2.Sum(x => x.Amount), 
           TimeStamp = g2.Key }) 
        .ToArray(); 

helper 
    .Setup(s => s.Compute(grouped, grouped.Count()) 
    .Returns(someValue); 

var result = _engine.Get(accountNumbers, startDate, endDate, code); 

helper.Verify(v => v.Compute(grouped, grouped.Count()), Times.Exactly(1)); 

實際的方法,我測試如下:

public decimal? Get(long[] accountNumbers, 
          DateTime startDate, 
          DateTime endDate, 
          long code) 
{ 
     var accountNumbersInt = Array.ConvertAll(accountNumbers, i => (int)i); 

     var myArray = TransactionManager 
          .Get(accountNumbersInt, startDate, endDate, code); 

     var accountValues = GroupData(myArray); 
     var result= Helper.Compute(accountValues, accountValues.Count()); 
     return result; 
} 

internal myArray[] GroupData(Account[] myArray) 
{ 
    var grouped = myArray 
         .SelectMany(x => x.AccountValues) 
         .GroupBy(x => x.TimeStamp) 
         .Select(g2 => 
          new AccountValue { 
            Amount = g2.Sum(x => x.Amount), 
            TimeStamp = g2.Key }) 
         .ToArray(); 
    return grouped; 
} 

編輯:助手設置爲測試設置如下

[SetUp] 
public void Setup() 
{ 
    _engine = new CalcEngine(); 
    helper = new Mock<IHelper>(); 
    _engine.Helper = helper.Object; 
} 
+0

什麼是幫手?通常在執行實際測試時會運行該命令,但在調試時首次跨越該特定行時不應更改。 – Gorgsenegger

+0

你是如何嘲笑幫手的?這是重要的信息,因爲我們不能看到你是否真的打電話給助手,或助手模擬 - 也許這是錯誤 – Stephan

+0

@Stephan - 編輯帖子的幫手代碼 –

回答

0

這裏的這個部分不會調用你的方法:

helper 
    .Setup(s => s.Compute(grouped, grouped.Count()) 
    .Returns(someValue); 

您的測試寫入的方式,我假定您正在測試您的_engine.Get()方法。 這個想法是,你會創建一個模擬,將它傳遞給你正在測試的方法(不同的方式來做),調用你正在測試的方法,然後觀察還有什麼被稱爲結果(副作用)。

我看到在您的Get()方法你做以下幾點:

var result= Helper.Compute(accountValues, accountValues.Count()); 

。假定Helper的是,你要確認你需要從你的單元測試通過它一樣的,所以像:

helper 
    .Setup(s => s.Compute(grouped, grouped.Count()) 
    .Returns(someValue); 

_engine.Helper = helper.Object; 

// your verifications here ... 
+0

幫手是這樣設置的,這就是爲什麼它是如此奇怪 –

+0

@ newbie_86我看到它的方式,你需要模擬你的'TransactioManager'並設置它以返回你在單元測試中創建的數組。目前,驗證會失敗,因爲您沒有使用相同的對象調用方法(相同的結果集) –