2013-06-12 135 views
-1

我正在爲現有項目創建單元測試。無法將類型void隱式轉換爲int

  • n1n2是輸入數字
  • op處於開關殼體的操作數在主程序

問題是與actual。我無法匹配預期值和實際值,因爲我收到錯誤cannot implicitly convert void to int

我的單元測試:

[TestMethod()] 
public void docalcTest(int actual) 
{ 
    Form1 target = new Form1(); // TODO: Passenden Wert initialisieren 

    double n1 = 15; // TODO: Passenden Wert initialisieren 
    double n2 = 3; // TODO: Passenden Wert initialisieren 
    int op = 2; // TODO: Passenden Wert initialisieren 
    int expected = 5; 

    actual = target.docalc(n1, n2, op); 

    Assert.AreEqual(expected,actual); 
} 

爲docalc代碼:

public void docalc(double n1, double n2, int op) 
{ 
    result = 0; 
    setText("clear"); 

    switch (op) 
    { 
     case 1: 
      result = n1 + n2; 
      break; 
     case 2: 
      result = n1 - n2; 
      break; 
     case 3: 
      result = n1 * n2; 
      break; 
     case 4: 
      result = n1/n2; 
      break; 
    } 

    setText(result.ToString()); 
} 
+5

什麼是'target.docalc'? – PhonicUK

+2

'docalc'返回什麼?如果你想讓它返回任何東西,它不能是一個'void'方法。 – Oded

+0

target.docalc(...)返回什麼?我猜無效這就是爲什麼你會得到這個錯誤 – DaveHogan

回答

0

我想這docalc返回void ......改變返回類型爲int,你應該罰款

3

你的方法target.docalc()是一個無效的方法,而actual是一個int。正如編譯器所說,您不能將void分配給int

根據您的評論(你真的應該只是修改你的問題),你docalc()看起來是這樣的:

public void docalc(double n1, double n2, int op) 
{ 
    result = 0; 

    ... 

    setText(result.ToString()); 
} 

你必須在方法的返回類型更改爲int,並返回結果:

public int docalc(double n1, double n2, int op) 
{ 
    int result = 0; 

    ... 

    return result; 
} 

旁註,你爲什麼這樣做?

[TestMethod()] 
public void docalcTest(int actual) 
{ 
    ... 

    actual = ... 

該測試方法將被調用沒有參數,所以它在那裏有點沒用。您可能需要將其更改爲:

[TestMethod()] 
public void docalcTest() 
{ 
    ... 

    int actual = ... 
+0

我知道我不能使用void與int。 while'[TestMethod()] public void docalcTest() { ... int actual = ...'也不起作用。已經嘗試過,同樣的錯誤。這就是爲什麼尋找方式。在此先感謝 – Ruud

+0

@Ruud再次閱讀我的答案。關於「int actual」聲明的評論並不是答案,改變'docalc()'方法的返回類型是。 – CodeCaster

+0

好吧,明白了。謝謝。這意味着現在應該改變整個代碼:) – Ruud

相關問題