How to inject PersistenceContext during unit testing?

前端 未结 3 1496
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 14:55

This is my java class:

public class Finder {
  @PersistenceContext(unitName = \"abc\")
  EntityManager em;
  public boolean exists(int i) {
    return (this.em.f         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 15:38

    It depends on what you want to test. When you have complex business logic in your Finder class you may want to mock the EntityManager - using a mocking framework like EasyMock or Mockito - in order to unit test that logic.

    Now since that's not the case I suspect you want to test the persistency of the Employee entity (this is often referred to as integration testing). This requires the use of a database. To make testing easy and keep your tests portable you can use an in-memory database like HSQLDB for this purpose. In order to start HSQLDB, create a persistence context and inject this context into your Finder class it's advisable to use an IoC framework like Spring.

    There are tons of tutorials on the internet that explain how to use JPA/Spring/HSQLDB. Take a look at this example project: Integration testing with Maven 2, Spring 2.5, JPA, Hibernate, and HSQLDB

提交回复
热议问题