【发布时间】:2012-04-06 00:08:50
【问题描述】:
我有一个返回类型为对象的方法。如何为此创建测试用例?我如何提到结果应该是一个对象?
例如:
public Expression getFilter(String expo)
{
// do something
return object;
}
【问题讨论】:
标签: java object junit testcase
我有一个返回类型为对象的方法。如何为此创建测试用例?我如何提到结果应该是一个对象?
例如:
public Expression getFilter(String expo)
{
// do something
return object;
}
【问题讨论】:
标签: java object junit testcase
试试这样的东西。如果您的函数的返回类型是Object,则将Expression 替换为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
//check if the returned object is of class Expression.
assertTrue(true, myReturnedObject instanceof Expression);
} catch(Exception e){
// let the test fail, if your function throws an Exception.
fail("got Exception, i want an Expression");
}
}
【讨论】:
在您的示例中,返回类型是 Expression?没看懂,能详细点吗?
该函数甚至无法返回 Expression 以外的任何内容(或派生类型或 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#;您没有标记您的问题,也没有提及问题中的语言。
【讨论】: