JUnit Best Practices – Use expected exception instead of catching the exception

Use JUnit expected exception feature to test a unit that might throw an exception in given situation or for a given input.

package com.ourownjava.unit.under.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

import com.ourownjava.exception.NoAppleException;
import com.ourownjava.model.Apple;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class AppleServiceTest {
	
	private AppleService appleService;
	
	@Before
	public void setUp(){
		appleService = new AppleService();
	}
	
        //This one is not a good practice
	@Test
	public void shouldGetNoAppleException_(){
		try {
			final List apples = appleService.getApple(101);
		} catch (Exception e) {
			assertTrue(e instanceof NoAppleException);
		}
	}
	
        //This one is a good practice
	@Test(expected = NoAppleException.class)
	public void shouldGetNoAppleException() throws NoAppleException{
		final List apples = appleService.getApple(101);
		fail("Expected NoAppleException");
	}
}

package com.ourownjava.unit.under.test;

import java.util.ArrayList;
import java.util.List;

import com.ourownjava.exception.NoAppleException;
import com.ourownjava.model.Apple;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class AppleService {
	
	private static final Integer MAX_APPLE_LOT = 100;
	
	public List getApple(final Integer numberOfApples) throws NoAppleException{
		if(numberOfApples > MAX_APPLE_LOT){
			throw new NoAppleException();
		}
		final List apples = new ArrayList();
		for(int i = 0; i < numberOfApples; i++){
			final Apple apple = new Apple();
			apples.add(apple);
		}
		return apples;
	}

}

package com.ourownjava.exception;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class NoAppleException extends Exception {
	
	private static final long serialVersionUID = 1L;

	public NoAppleException(){
		super("Your eyes doesn't meet the stomach");
	}

}

package com.ourownjava.model;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class Apple {}


Leave a comment

Your email address will not be published. Required fields are marked *