How to inject PersistenceContext during unit testing?

Viewed 27254

This is my java class:

public class Finder {
  @PersistenceContext(unitName = "abc")
  EntityManager em;
  public boolean exists(int i) {
    return (this.em.find(Employee.class, i) != null);
  }
}

This is the unit test:

public class FinderTest {
  @Test public void testSimple() {
    Finder f = new Finder();
    assert(f.exists(1) == true);
  }
}

Testing fails with NullPointerException since Finder.em is not injected by anyone. How should I handle this situation properly? Does there any best practice exist?

3 Answers

Create another package-private constructor and add only EntityManager then call the other constructor for default behavior.

@PersistentContext
private EntityManager entityManager;

private ManagementService managementService;

@Autowired
public SomeClass(ManagementService managementService) {
    this.managementService = managementService;
}

SomeClass(ManagementService managementService, EntityManager entityManager) {
    this(managementService);

    this.entityManager = entityManager;
}

Related