Java – how to get “real” exceptions in JUnit instead of ejbexceptions when using ejbcontainer?

I am setting up unit tests in my Java EE application I am using JPA, JSF, NetBeans and GlassFish It is also my first real Java application. Please forgive me if the answer is obviously stupid!

The test uses ejbcontainer to access the entity and try to enter an empty record Then it tries to enter a record whose user name is too short I want to make sure that the correct exception is thrown

I can add @ test (expected = javax. EJB. EJBException. Class), but this will catch any exceptions that the container may throw If it's not the expected exception I want to know (as with the philosophy of capturing a multipurpose exception, the best practice is to capture specific exceptions)

The following tests help to 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
}

The following is a comment for the "username" attribute 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 tests should throw javax validation. Constraintviolationexception or some other exceptions I can see them in the debug information in EJBException I'm not sure if there is a way to "extract" the right exceptions?

Finally, I am a total rookie So if I'm hiking on the wrong road, please let me know

thank you.

–Update–

In response to Stephen, this 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.");
        }
    }

Solution

You must explicitly catch EJBException in the unit test, call getCause () to extract the real exception, and then test it as needed

(this is how you test to throw the correct exception in the version 3 JUnit test.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>