java 如何为返回对象的方法编写测试用例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10037712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write a test case for a method returning object
提问by Jessie
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;
}
回答by Simulant
try Something like this. If the return-type of your function is Object
then replace Expression
by Object
:
尝试这样的事情。如果您的函数的返回类型被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
//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");
}
}
回答by RobIII
In your example the returntype is Expression? I don't understand the question, could you elaborate?
在您的示例中,返回类型是表达式?没看懂问题,能详细点吗?
The function is even unableto 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.
我在这里假设 C#;你没有标记你的问题,也没有提到你的问题中的语言。