Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android JUnit: How to have an exception cause a test case to pass (@Test annotation)

I'm trying to write some JUnit tests for an Android application.

I've read online that to have a unit test pass if it throws an exception, you would use the @Test annotation like this

@Test(expected = NullPointerException.class)
public void testNullValue() throws Throwable
{
    Object o = null;
    o.toString();
}

but Eclipse is telling me that this annotation doesn't exist. How can I fix this? If I run the test, it runs fine and fails as expected but obviously I want it to fail (and thus actually pass) :)

like image 642
you786 Avatar asked Dec 27 '22 16:12

you786


1 Answers

You can always bypass it manually:

public void testNullValue()
{
    try {
       Object o = null;
       o.toString();
       fail("Expected NullPointerException to be thrown");
    } catch (NullPointerException e) {
       assertTrue(true);
    }
}
like image 64
filip-fku Avatar answered Jan 03 '23 08:01

filip-fku