You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot JUnit测试@Autowired Bean为空及EntityManager空指针问题求助

Fixing NullPointerException when unwrapping Session from EntityManager in RoleDataControllerTest

Hey there! Let's break down why you're hitting that NullPointerException on the line public Session session = entityManager.unwrap(Session.class); and how to fix it. The root issue here is almost always that your entityManager instance is null when you try to call unwrap() on it. Here are the most common fixes:

1. Ensure EntityManager is properly injected in your Spring-based test

If you're using Spring Boot or Spring Framework for your tests, you need to let the Spring container manage and inject the EntityManager for you. Follow these steps:

  • Add the right test annotations to your test class (like @SpringBootTest for full application context, or @DataJpaTest for focused JPA tests)
  • Use @PersistenceContext or @Autowired to inject the EntityManager (prefer @PersistenceContext for JPA-specific injection)
  • Initialize the Session in a setup method (like @BeforeEach) instead of directly assigning it to a public field, so you know EntityManager is already injected

Example code:

@SpringBootTest
class RoleDataControllerTest {
    @PersistenceContext
    private EntityManager entityManager;

    private Session session;

    @BeforeEach
    void setUp() {
        // Now entityManager is guaranteed to be initialized by Spring
        session = entityManager.unwrap(Session.class);
    }

    // Your test methods go here...
}

2. Manually initialize EntityManager if you're not using Spring

If you're writing a plain JPA test without Spring, you need to manually create the EntityManagerFactory and EntityManager before using them:

  • Create an EntityManagerFactory using your persistence unit name (defined in persistence.xml)
  • Initialize the EntityManager from the factory
  • Don't forget to clean up resources in a teardown method to avoid leaks

Example code:

class RoleDataControllerTest {
    private EntityManager entityManager;
    private Session session;

    @BeforeEach
    void setUp() {
        // Replace "your-persistence-unit" with the name from your persistence.xml
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("your-persistence-unit");
        entityManager = emf.createEntityManager();
        session = entityManager.unwrap(Session.class);
    }

    @AfterEach
    void tearDown() {
        // Clean up resources after each test
        if (entityManager != null && entityManager.isOpen()) {
            entityManager.close();
        }
    }

    // Your test methods go here...
}

3. Avoid public fields for injected dependencies

Having a public entityManager field isn't the best practice, and sometimes Spring might not inject into public fields correctly. Switching to a private field with the right annotation (@PersistenceContext or @Autowired) will make your test more reliable.

4. Double-check your persistence configuration

Make sure your persistence.xml (for traditional JPA) or application.properties/application.yml (for Spring Boot) has a valid persistence unit defined with the correct datasource settings. If the persistence unit is missing or misconfigured, the EntityManager won't be created properly.


内容的提问来源于stack exchange,提问作者Harini2017

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:32:04