Junit Expected Exception Testcases Example

Junit is a unit testing framework for the Java programming language. If you want to read about best practices followed for junit testing then here is an excellent guide for your reference.

In this post, I am writing a sample test case which expects exceptions to be thrown on runtime. If it gets the expected exception, test passes. If expected exception is not detected, test cases fails.

These type of test cases are very useful where you want your application to fail for very absurd input.

package com.howtodoinjava.test.junit;

import org.junit.Test;

public class ExpectedExceptionTest
{
	//This test case fails because it was expecting ArithmeticException
	@Test(expected = ArithmeticException.class)
	public void expectArithmeticException()
	{
		System.out.println("Everything was fine here !!");
	}

	//This test case fails because it was expecting ArithmeticException
	@Test(expected = ArithmeticException.class)
	public void expectArithmeticException2()
	{
		throw new NullPointerException();
	}

	//This test case passes because it was expecting NullPointerException
	@Test(expected = NullPointerException.class)
	public void expectNullPointerException()
	{
		//some code which throw NullPointerException in run time
		throw new NullPointerException();
	}
}

In above 3 testcases, first two fails because they were expecting ArithmeticException which they didn’t get while test case execution.

Third testcase gets pass because, it was expecting the NullPointerException and testcase threw it.

This way you can write your testcases which are dependent on some exceptions to test the behavior of application on failure.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

4 thoughts on “Junit Expected Exception Testcases Example”

  1. Writing tests for exceptions is tricky!

    There is one “problem” with using “expected”. If the unit under test can throw the same exception twice in the same flow(e.g. NullpointerExceptions can usually be thrown almost enywhere). Then you don’t know which exception it was that caused the test to pass.

    One option could be to use try-catch and assert message in the thrown exception to assert that it was the “right” exception that was thrown, but, I don’t like using try catch in unit tests since it is easy misuse and you need to keep in mind the exception hierarcy etc. etc.

    Additional problems with writing tests for exceptions is that you make an assumption that the exception in question is thrown by your dependeny. What if someone refactors the dependency implementation? Your unit test will still pass, but, when hitting production it will fail.

    My way of writing tests for these cases (so far) is to use “expected” and back your Unit test up with an integration test that verifies that you assumption about the exception type is correct.

    BR

    The Mackerel

    Reply
    • Hi Mack, thanks for your valuable inputs. My thinking is that when you write testcases like this, you have a very specific input (mostly hardcoded). For such input, you can be very sure that it must throw only a specific exception.

      Regarding refactoring, I believe that testcase should not check dependencies. It should assume that all the configurations are perfect and should focus on testing the business logic ONLY. Maybe one or two testcases may run in very first, to check if test environment is configured correctly. No need to test in other places.

      Reply
      • Hi again!
        I think we are on the same track! I totally agree with you – test cases should only test business logic. Perhaps I was unclear on that.

        re: Regardin Refactoring
        I don’t suggest that you should test dependencies in your unit test. As you mention, only bussiness logic should be tested. In this case we test how exceptions are handled. The problem with exceptions are that you as a developer will have make a hardcoded assumption (using fakes, stubs or mocks) of which exception that is thrown. This hardcoding will lead to that your test will never fail. – this is my concern since it gives you a false sence of security.

        I suggested that you not only should use unit tests, but also integration tests (and other tests as well) to fetch defects before hitting production.

        As I mentioned in my initial post, I think writing good tests are tricky…there are lots of pitfalls…in my opinion, writing unit tests for exception handling is one of them….but perhaps that’s just me….

        BR

        The Mackerel

        Reply
        • Fair enough. When I say “test dependencies” it means, check the whole test setup before executing other tests which actually test business logic. This prevents unnecessary big failure reports with large number of red circles. I hate them. Just wanted to clarify.

          Now regarding “hardcoded assumption”. I believe they are also necessary. Just like we validate all input parameters in start of any method, and then use it freely inside method code. And it helps in code coverage also. But, it should not be done excessively otherwise developer checkins more with less value addition.

          NO, you are not alone. I am along with you. Writing unit tests for exception handling is also tricky and can easily be misused.

          Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.