How to test Exceptions with ActivityTestCase or InstrumentationTestCase

244 views Asked by At

I'm creating some Junit Tests with Android Studio 1.2.2. This is my TestClass. It extends from ActivityTestCase (or InstrumentationTestCase).

public class TypeTest extends ActivityTestCase 
{
    TypesMeth typesMeth = new TypesMeth();

    public void testTypes() 
    {
        typesMeth.setValue((short) 1000000);
        assertEquals(exception, typesMeth.getValue());
    }
}

The parameter must be short. So the range is from -32768 to 32767.

If I pass a value of 1000000 it should throw an exception and the test should be passed.

How can I check that? Something like: assertExceptionIsThrown(true, typesMeth.getValue());

1

There are 1 answers

0
Westranger On BEST ANSWER

In classical JUnit 4 you would add some annotation before your testcase

@Test(expected = IllegalArgumentException.class)
public void myUnitTest() {
   ...
}

As far as I know there are no annotation in Android which support this, so you need to do it in a pre JUnit 4 way with try and catch

try {
  doSomethingThatShouldThrow();
  fail("Should have thrown Exception");
} catch (IllegalArgumentException e) {
  // success
}