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;
}
Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80
Jessie
  • 963
  • 5
  • 16
  • 26

2 Answers2

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");
     }
}
Simulant
  • 19,190
  • 8
  • 63
  • 98
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.

RobIII
  • 8,488
  • 2
  • 43
  • 93
  • hi I need junit testcase. I jus mentioned Expression its actually object. – Jessie Apr 06 '12 at 00: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](http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm) but I'm no Java guru :-) You might also want to check out http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom – RobIII Apr 06 '12 at 00:32