简体   繁体   中英

Is it ok to test EJB3/JPA with standalone JPA?

I have an JEE5 app using EJB3 with JPA. Eg I have some beans with

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)

I'd like to write some tests for those services. I know I can use embeddable container like OpenEJB, but as JPA is available in Java SE, I wonder if I can use it in testing? Certainly I won't have all the

@PersistenceContext, @PersistenceUnit, @TransactionAttribute

features available. So my question is if this is worth trying (hand-made transaction management and so on)? Or should I go with embedded container? I'm talking about integration tests (with real, but in-memory database), not about mocking all stuff around.

EDIT:

One more thing as I'm quite new to testing in embedded container. Is it possible to inject eg Mockito's mock as an @EJB dependency to my bean under test? Or maybe it doesn't make sense in this setup?

You can test a lot of things with Java SE / JPA. But there is a major part of what we call Integration Testing that will require massive amount of effort to mock up things, and some that just won't be doable without Arquillian or similar help. Do you want your EJB transactional functionality/etc to be included among the things you test? If so you have to implement tests that lives in a transactional environment as close to production as possible. I strongly suggest using a ejb-testing-framework.

If you want to test your service beans, I think a good approach is to use some mocking framework like EasyMock and mock the entity manager, so in that case you test just the piece of code you want to and not the entire thing.

You just need to add two constructors to your session bean, one default and one with the dependencies it needs so then you can provide mock objects there.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM