2012-04-06 144 views
0

我有一種返回類型是對象的方法。我如何爲此創建測試用例?我如何提到結果應該是一個對象?如何爲返回對象的方法編寫測試用例

例如爲:

public Expression getFilter(String expo) 
{ 
    // do something 
    return object; 
} 
+1

這是不明確。你的方法返回一個表達式。 Java中的所有東西都是「對象」,包括你的「表達式」。你想要測試什麼? – Guillaume 2012-04-06 22:55:37

回答

1

嘗試類似這樣的東西。如果返回類型的功能是Object然後通過Object更換Expression

//if you are using JUnit4 add in the @Test annotation, JUnit3 works without it. 
//@Test 
public void testGetFilter(){ 
    try{ 
     Expression myReturnedObject = getFilter("testString"); 
     assertNotNull(myReturnedObject);//check if the object is != null 
     //checks if the returned object is of class Expression 
     assertTrue(true, myReturnedObject instaceof Expression); 
    }catch(Exception e){ 
     // let the test fail, if your function throws an Exception. 
     fail("got Exception, i want an Expression"); 
    } 
} 
1

在您的例子中,返回類型是表達?我不明白這個問題,你能否詳細說明一下?

函數是甚至無法返回除表達式(或派生類型或null)以外的任何東西。所以「檢查類型」將毫無意義。

[TestMethod()] 
public void FooTest() 
{ 
    MyFoo target = new MyFoo(); 
    Expression actual = target.getFilter(); 

    Assert.IsNotNull(actual); //Checks for null 
    Assert.IsInstanceOfType(actual, typeof(Expression)); //Ensures type is Expression 
} 

我在這裏假設C#;你沒有標記你的問題,也沒有提到你的問題中的語言。

+0

您好我需要junit測試用例。我提到表達式其實際的對象。 – Jessie 2012-04-06 00:28:07

+1

因此,下次爲'java'和'junit'標記問題,並確保示例代碼準確地重現或演示了您的問題;-)(這次爲您做了)。我認爲關鍵是[instanceof](http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm),但我不是Java大師:-)你可能也想看看http:/ /stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom – RobIII 2012-04-06 00:32:54

相關問題