JUnit Expected Exception Rule Example

0

The ExpectedException is a test rule that allows us to verify that the code throws a specific exception. Like any rule, we have to define it as a public final member using @Rule annotation. See TestName Example for a brief about test rule. Once we have set the expected exception and the test doesn’t throw the expected exception then it will fail and the test is successful when the specified exception is thrown. In this article we will see an example of expected exception.

ExpectedException Example

In the below example, we have a server class. Its life cycle starts from ‘INITIALIZED’ and ends at ‘STOPPED’. To start the server, we will call start(). It will throw an exception if the server is already started or running.

Server:

package com.javarticles.junit;

public class Server {
    private Status currentStatus;   
    
    public Server() {
        currentStatus = Status.INITIALIZED;
    }
    public void start() {
        if (currentStatus == Status.RUNNING || currentStatus == Status.STARTED) {
            throw new IllegalStateException("Server is already started");
        }
        currentStatus = Status.STARTED;
    }
    
    public void stop() {
        currentStatus = Status.STOPPED;
    }
    
    enum Status {
        INITIALIZED,
        STARTED,
        RUNNING,
        STOPPED
    }
}

Our test below verifies that when we call start() on an already started server, an IllegalStateException is thrown. We can also verify the expected message.

ExceptedExceptionExample:

package com.javarticles.junit;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class ExceptedExceptionExample {
    @Rule
    public final ExpectedException thrown = ExpectedException.none();    
    
    @Test
    public void startAlreadyRunningServer() {
        Server server = new Server();
        System.out.println("Start server");
        server.start();
        System.out.println("Configure the expected execption to be IllegalStateException");
        thrown.expect(IllegalStateException.class);
        thrown.expectMessage("Server is already started");
        System.out.println("Start server again");
        server.start();
        System.out.println("Shouldn't reach here as IllegalStateException is thrown");
    }
}

Output:

Start server
Configure the expected execption to be IllegalStateException
Start server again

Download the source code

This was an example about ExpectedException rule.

You can download the source code here: junitExpectedExceptionRuleExample.zip
Share.

Comments are closed.