问题
I have a method for which the return type is object. How do I create a test case for this? How do I mention that the result should be an object?
e.g.:
public Expression getFilter(String expo)
{
// do something
return object;
}
回答1:
try Something like this. If the return-type of your function is Object
then replace Expression
by Object
:
//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");
}
}
回答2:
In your example the returntype is Expression? I don't understand the question, could you elaborate?
The function is even unable to return anything other than Expression (or a derived type or null). So "checking the type" would be pointless.
[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
}
I am assuming C# here; you haven't tagged your question nor mentioned the language in your question.
来源:https://stackoverflow.com/questions/10037712/how-to-write-a-test-case-for-a-method-returning-object