Sunday, August 2, 2020

2 Ways to test Exception in JUnit : Annotation vs try-catch

Error handling is a core part of coding but most of the time it just went under the radar when it comes to unit testing. How do we write a JUnit test that verifies that an exception is thrown? With the try-catch construct, of course, except that this time, the code throwing an exception is a good thing—the expected behavior. The approach shown in the below code is a common pattern for testing exception-throwing behavior with JUnit.


Testing for Exception
@Test
public void missingValueRaisesException() throws Exception {
try {
new Template("${foo}").evaluate();
fail("evaluate() should throw an exception if "
+ "a variable was left without a value!");
} catch (MissingValueException expected) {
}
}

Note the call to the fail method right after evaluation. With that call to org.junit.Assert#fail, we’re basically saying, “if we got this far, something went wrong” and the fail method fails the test. If, however, the call to evaluate throws


Testing for exceptions with an annotation

JUnit 4 brought us a handy annotation-based syntax for expressing exception
tests such as our missingValueRaisesException in listing 2.14. Using the annotation
syntax, the same test could be written as follows:

@Test(expected=MissingValueException.class)
public void testMissingValueRaisesException() throws Exception {
new Template("${foo}").evaluate();
}

Although this annotation-based version of our test is less verbose than our try-catch,
with the try-catch, we can also make further assertions about the exception
thrown (for example, that the error message contains a key piece of information).
Some folks like to use the annotation syntax where they can, while
others prefer always using the same try-catch pattern. Personally, I use the
annotation shorthand when I’m only interested in the type and use the try-catch
when I feel like digging deeper.


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;

/**
*
*
* @author Javin Paul
*/

public class Testing {

   public static void main(String args[]) {
        // Prefer containsKey(), containsValue() over != null check
        HashMap numbers = new HashMap<>();
        numbers.put(1, "one");
        numbers.put(2, "two");
        int number = 0;
        // Instead of
        if (numbers.get(number) != null) {
            // do something
        }
        // do this - more readable
        if (numbers.containsKey(1)) {
        }
        // Similarly use isEmpty instead of checking string length
        String str = "abc";

        // Instead of
        if (str.length() > 0) {
            // do something
        }

        // do this
        if (!str.isEmpty()) {
            // do  something
        }
    }

}

That's all about how to test exceptions in a Java program using JUnit. As I said, there are 2 ways to test if a method is throwing an exception or not or a particular code block. You can either use the expected attribute of @Test annotation or just throw the exception using the "fail" keyword.


Further Learning
Unit Testing In Java With JUnit
JUnit and Mockito Crash Course
Learn Unit Testing with Junit & Mockito in 30 Steps


Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.