Android Unit testing in Android with JUnit edit


JUnit can also be used to test if a method throws a specific exception for a given input.

In this example we will test if the following method really throws an exception if the Boolean format (input) is not recognized/unknown:

public static boolean parseBoolean(@NonNull String raw) throws IllegalArgumentException{
    raw = raw.toLowerCase().trim();
    switch (raw) {
        case "t": case "yes": case "1": case "true":
            return true;
        case "f": case "no": case "0": case "false":
            return false;
            throw new IllegalArgumentException("Unknown boolean format: " + raw);

By adding the expected parameter to the @Test annotation, one can define which exception is expected to be thrown. The unit test will fail if this exception does not occur, and succeed if the exception is indeed thrown:

@Test(expected = IllegalArgumentException.class)
public void parseBoolean_parsesInvalidFormat_throwsException(){
    StringUtilities.parseBoolean("Hello JUnit");

This works well, however, it does limit you to just a single test case within the method. Sometimes you might want to test multiple cases within a single method. A technique often used to overcome this limitation is using try-catch blocks and the method:

public void parseBoolean_parsesInvalidFormats_throwsException(){
    try {
        fail("Expected IllegalArgumentException");
    } catch(IllegalArgumentException e){

    try {
        fail("Expected IllegalArgumentException");
    } catch(IllegalArgumentException e){

Note: Some people consider it to be bad practice to test more than a single case inside a unit test.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents
64 Menu
80 Unit testing in Android with JUnit
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close