Book Image

Mastering Unit Testing Using Mockito and JUnit

By : Sujoy Acharya
Book Image

Mastering Unit Testing Using Mockito and JUnit

By: Sujoy Acharya

Overview of this book

Table of Contents (17 chapters)
Mastering Unit Testing Using Mockito and JUnit
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Handling exceptions


Exception handling is an important part of Java coding. The Java community follows a set of best practices about exception handling. The following are the exception handling best practices for unit testing:

  • Do not write catch blocks to pass a unit test. Consider the following example where a Calculator program has a divide method. It takes two integers, divides, and returns a result. When divide encounters a divide by zero, the program should throw an exception. The following is the code:

    public class Calculator {
    
      public int divide(int op1, int op2)  {
        return op1/op2;
      }
    }

    The following is the test:

    @Test
    public void divideByZero_throws_exception() throws Exception {
      try {
        calc.divide(1, 0);
        fail("Should not reach here");
      } catch (ArithmeticException e) {
    
      }
    }

    Instead of catching ArithmeticException, we can apply the JUnit 4 pattern as follows:

      @Test(expected = ArithmeticException.class)
      public void divideByZero_throws_exception() throws Exception...