I’m setting up a unit test in my Java EE application. I’m using JPA, JSF, Netbeans and Glassfish. It’s also my first real java application so forgive me if the answer is stupid obvious!
The test uses an EJBContainer, accesses the entity and tries to enter a null record. Then it tries to enter a record with a username that is too short. I want to confirm that the proper exceptions are thrown.
I can add @Test(expected=javax.ejb.EJBException.class) but that will catch any exception the container may throw. If it’s NOT the expected exception I want to know about it. (same philosophy as catching an all purpose Exception, best practice is to catch the specific exception)
Here is the test to help illustrate:
//@Test(expected=javax.validation.ConstraintViolationException.class)
@Test(expected=javax.ejb.EJBException.class)
public void testCreate() throws Exception {
EJBContainer container = getContainer();//pull singleton container
AgentsFacade instance = (AgentsFacade) container.getContext().lookup("java:global/classes/AgentsFacade");
Agents badAgent = new Agents();
instance.create(badAgent);//null username
//Short username
Agents shortUsername = new Agents("srtnm");
instance.create(shortUsername);//must be > 6 in length
}
Here are the annotations for the “username” property of the Agents entity:
...
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(unique=true)
@Size(min=6, max=40)
@NotNull
private String username;
...
As you can see, both test should throw either javax.validation.ConstraintViolationException or some other exception. I can see them in the debugging information within the EJBException. I’m not sure if there is a way to “extract” the correct exceptions?
Finally, I’m a total noob. So if I’m trekking down the wrong road let me know.
Thanks.
–Update–
In response to Stephen, here is the result I came up with.
try {
//Null username
Agents badAgent = new Agents();
instance.create(badAgent);
fail("NULL agent added!");//should never reach this point.
} catch (EJBException e) {
Exception causedByException = e.getCausedByException();
if(!(causedByException instanceof javax.validation.ConstraintViolationException)){
fail("ConstraintViolationException wasn't thrown.");
}
}
You will have to explicitly catch the
EJBExceptionin the unit test, callgetCause()to extract the real exception and then test it as required.(This is the way you test that the correct exceptions are thrown in a version 3 JUnit test.)