3

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;
}
0

2 Answers 2

5

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
        //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");
     }
}
0
1

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.

2
  • hi I need junit testcase. I jus mentioned Expression its actually object.
    – Jessie
    Apr 6, 2012 at 0:28
  • 1
    So tag your question with 'java' and 'junit' next time and make sure the example code accurately reproduces or demonstrates your problem ;-) (Did it for you this time). I think the key would be instanceof but I'm no Java guru :-) You might also want to check out stackoverflow.com/questions/496928/…
    – RobIII
    Apr 6, 2012 at 0:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.