Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
MASTERING UNIT TESTING USING MOCKITO AND JUNIT

You're reading from   MASTERING UNIT TESTING USING MOCKITO AND JUNIT An advanced guide to mastering unit testing using Mockito and JUnit

Arrow left icon
Product type Paperback
Published in Jul 2014
Publisher
ISBN-13 9781783982509
Length 314 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Sujoy Acharya Sujoy Acharya
Author Profile Icon Sujoy Acharya
Sujoy Acharya
Arrow right icon
View More author details
Toc

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...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image