junit test cases to test throw new Exception and return

Hello All,

I need to have 100% coverage on my code. How could I do junit test cases that tests throw new Exception(....) and return;

	private void getTrafficProfileByTrafficProfileID(List<Integer> trafficProfileID) throws Exception{

		if (trafficProfileID == null || trafficProfileID.isEmpty()){
			return;
		}
		for(Integer id : trafficProfileID){
			logger.info("Retrieving Traffic Profile by TrafficProfileID: " + id);
			List<TrafficProfile> tps = getTrafficProfileDAO().getTrafficProfileByTrafficProfileId(id.longValue());
			if (tps == null || tps.isEmpty()) {
				throw new Exception("Incorrect Traffic Profile ID. This ID does not exist: " + id);
			}
			List<CosClassAllocation> allocation = getCosClassAllocationDAO().getCosClassAllocationByTrafficProfileId(id.longValue());
			if (allocation == null || allocation.isEmpty()){
				throw new Exception("Cos Class Allocation does not exist for Traffic Profile ID: " + id);
			}
		}
	} 

Open in new window

yescobar01Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jim CakalicSenior Developer/ArchitectCommented:
Write tests that mock the CosClassAllocationDAO. In one test have it return null and in another test have it return an empty List. Inject the mock into your class under test and execute the method to be tested. You could use Mockito for this or go old school and have a custom test class. Either way you'll need to have a DAO interface.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jim CakalicSenior Developer/ArchitectCommented:
Here's what the unit test might look like using Mockito
import static org.mockito.Mockito.*;

import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;

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

public class TrafficServiceTest {
    @Mock
    TrafficProfileDAO trafficProfileDAO;

    @Mock
    CosClassAllocationDAO cosClassAllocationDAO;

    @InjectMocks
    TrafficService trafficService;

    @Test(expected = Exception.class)
    public void throwsExceptionWhenTrafficProfilesNull() throws Exception {
        when(trafficProfileDAO.getTrafficProfileByTrafficProfileId(1)).thenReturn(null);
        trafficService.getByTrafficeProfileID(1);
    }

    @Test(expected = Exception.class)
    public void throwsExceptionWhenTraffileProfilesEmpty() throws Exception {
        List<TrafficProfile> empty = new ArrayList();

        when(trafficProfileDAO.getTrafficProfileByTrafficProfileId(1)).thenReturn(empty);
        trafficService.getByTrafficeProfileID(1);
    }

}

Open in new window

This assumes your class under test is TrafficService with the method as you and a public method called by the test that takes just one Integer id (you can change that as appropriate). Your class under test is also assumed to have two fields for the DAOs. Something like:
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

public class TrafficService {
    private static final Logger logger = Logger.getLogger(TrafficService.class.getName());
    private TrafficProfileDAO trafficProfileDAO;
    private CosClassAllocationDAO cosClassAllocationDAO;

    public void getByTrafficeProfileID(Integer id) throws Exception {
        getTrafficProfileByTrafficProfileID(Collections.singletonList(id));
    }

    private void getTrafficProfileByTrafficProfileID(List<Integer> trafficProfileID) throws Exception{
        if (trafficProfileID == null || trafficProfileID.isEmpty()){
            return;
        }
        for(Integer id : trafficProfileID){
            logger.info("Retrieving Traffic Profile by TrafficProfileID: " + id);
            List<TrafficProfile> tps = getTrafficProfileDAO().getTrafficProfileByTrafficProfileId(id.longValue());
            if (tps == null || tps.isEmpty()) {
                throw new Exception("Incorrect Traffic Profile ID. This ID does not exist: " + id);
            }
            List<CosClassAllocation> allocation = getCosClassAllocationDAO().getCosClassAllocationByTrafficProfileId(id.longValue());
            if (allocation == null || allocation.isEmpty()){
                throw new Exception("Cos Class Allocation does not exist for Traffic Profile ID: " + id);
            }
        }
    }

    public TrafficProfileDAO getTrafficProfileDAO() {
        return trafficProfileDAO;
    }

    public CosClassAllocationDAO getCosClassAllocationDAO() {
        return cosClassAllocationDAO;
    }
}

Open in new window


The DAOs are assumed to be interfaces that have, at a minimum, the methods required by your class under test:
import java.util.List;

public interface CosClassAllocationDAO {
    List<CosClassAllocation> getCosClassAllocationByTrafficProfileId(Long id);
}

Open in new window

import java.util.List;

public interface TrafficProfileDAO {
    List<TrafficProfile> getTrafficProfileByTrafficProfileId(long id);
}

Open in new window

Jim CakalicSenior Developer/ArchitectCommented:
Sorry. The UT wasn't quite right. That's the danger of using the @Test(expected) ... unexpected Exceptions can look like success. So I added a successful test (no Exceptions) and modified the tests expecting Exceptions to catch and fail explicitly when the Exception is not thrown (which is what I usually do)
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

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

public class TrafficServiceTest {
    @Mock
    TrafficProfileDAO trafficProfileDAO;

    @Mock
    CosClassAllocationDAO cosClassAllocationDAO;

    @InjectMocks
    TrafficService trafficService;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void isSuccessful() throws Exception {
        List<CosClassAllocation> allocations = Collections.singletonList(new CosClassAllocation());
        List<TrafficProfile> profiles = Collections.singletonList(new TrafficProfile());
        when(trafficProfileDAO.getTrafficProfileByTrafficProfileId(any(Integer.class))).thenReturn(profiles);
        when(cosClassAllocationDAO.getCosClassAllocationByTrafficProfileId(any(Long.class))).thenReturn(allocations);
        trafficService.getByTrafficeProfileID(1);
    }

    @Test
    public void throwsExceptionWhenTrafficProfilesNull() throws Exception {
        List<CosClassAllocation> allocations = Collections.singletonList(new CosClassAllocation());
        when(trafficProfileDAO.getTrafficProfileByTrafficProfileId(any(Integer.class))).thenReturn(null);
        when(cosClassAllocationDAO.getCosClassAllocationByTrafficProfileId(any(Long.class))).thenReturn(allocations);
        try {
            trafficService.getByTrafficeProfileID(1);
            fail("expected exception");
        } catch (Exception e) {
            // ignored
        }
    }

    @Test
    public void throwsExceptionWhenTrafficProfilesEmpty() throws Exception {
        List<CosClassAllocation> allocations = Collections.singletonList(new CosClassAllocation());

        when(trafficProfileDAO.getTrafficProfileByTrafficProfileId(any(Integer.class))).thenReturn(new ArrayList());
        when(cosClassAllocationDAO.getCosClassAllocationByTrafficProfileId(any(Long.class))).thenReturn(allocations);

        try {
            trafficService.getByTrafficeProfileID(1);
            fail("expected exception");
        } catch (Exception e) {
            //ignored
        }
    }

}

Open in new window

yescobar01Author Commented:
Thanks for your help I am able to move forward.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.