Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test assert throws exception in Android

is there a more elegant way to do an assert throws exception in Android then this?

public void testGetNonExistingKey() {   
        try {
            alarm.getValue("NotExistingValue");
            fail( );
        } catch (ElementNotFoundException e) {

        }
}

Something like this does not work?!

    @Test(expected=ElementNotFoundException .class)

Thanks, Mark

like image 826
Mark Avatar asked Feb 02 '23 13:02

Mark


1 Answers

Are you using a junit4 test runner? The @Test annotation won't work if you're running a junit3 test runner. Check the version that you're using.

Secondly, the recommended way to check for exceptions in your code is to use a Rule (introduced in junit 4.7).

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void throwsIllegalArgumentExceptionIfIconIsNull() {
    // do something

    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("Icon is null, not a file, or doesn't exist.");
    new DigitalAssetManager(null, null);
}

You can continue to use the @Test(expected=IOException.class), but the above has the advantage that if an exception is thrown before the exception.expect is called, then the test will fail.

like image 181
Matthew Farwell Avatar answered Feb 07 '23 11:02

Matthew Farwell