How to easily test a EJB using JUnit

2019-05-16 17:38发布

问题:

I want to test an enterprise java bean (that should later be deployed to a JBoss server) using JUnit. But I don't exactly know how tools I can use for this. Plain JUnit fails because of the missing EJB Container and the caused lack of needed injections.

Googling a bit around lead me to a library called JBoss EJB embedded container, but it seems that it is obsolete. I also couldn't find any source or binary files to download.

So please help, what's a easy way to locally generate a "mock" container that is able to run the JUnit tests on the enterprise beans?

Greetings Ben

回答1:

I suggest you to have a look at Arquillian:

Arquillian enables you to test your business logic in a remote or embedded container. Alternatively, it can deploy an archive to the container so the test can interact as a remote client.

There is still a living Embedded JBoss AS. The Seam Framework also provides a testing environment with an embedded JBoss to run component tests (with TestNG) of your application.



回答2:

openEJB is an embedded EJB container that's a perfect fit for unit testing EJBs. You can test them outside your normal app server. And, it's fast! And, it spins up fast! And, it has an Eclipse plugin for easy management! Gotta love it! It's been around for a while, there are plenty of tutorials on how to set it up and use it, so you shouldn't have problems with it.



回答3:

You can use a EJB remote client in your JUnit program to test your EJB. Only drawback is that you have to have a running Application Server during testing.

Check out this blog entry for an example on how to invoke a EJB remotely.



回答4:

It's been awhile, but I always wrote my EJBs as simple wrappers of POJOs. An interface would define the methods, and both the POJO and the EJB (session, of course) would implement that interface.

I could fully test the "business logic" of the POJOs without any container issues. Then if I had the server running, I could run the same tests against the session bean, just by testing against the client instead of the POJO...



回答5:

Since I did not need the JNDI stuff (e.g. Cannot instantiate class: org.jnp.interfaces.NamingContextFactory) altogether in my DAO (ORM interface) tests it was enough for me to

  • include the hibernate jars in the classpath
  • remove/outcomment the <jta-data-source>...</jta-data-source> part in my persistence.xml
  • inject/assign your own entitymanagerfactory with Persistence.createEntityManagerFactory( "my-persistence-unit-name" )


标签: jboss junit ejb