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

JUnit4环境中@Autowired注入Repository报NullPointerException的原因

问题:JUnit4测试中@Autowired的Repository出现NullPointerException

我是Java开发新手,若术语使用不当还请见谅。每当我运行需要向数据库保存数据的类的测试时,@Autowired注入的Repository都会出现NullPointerException。我使用的是JUnit4,以下是代码片段:

代码片段

application-test.properties

spring.datasource.url=jdbc:tc:mysql:8.0.29://localhost:3306/MYSERVICE

MyService.java

@Component
class MyService {
    @Autowired MyRepository myRepository;
    
    public void mainFunction() {
        myRepository.saveSomething();
    }
}

MyRepository.java

@Repository
public interface MyRepository extends JpaRepository<T, Long> {
    
    void saveSomething();
}

MyServiceTest.java

public class myServiceTest extends TestConfiguration {
    @Rule
    public MySQLContainer mysql = new MySQLContainer();

    @InjectMocks MyService myService;

    @Test
    public void mainFunctionTest() {
        myService.mainFunction();
    }
}

MyServiceTestApplication.java

@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class
})
public class MyServiceTestApplication{
}

TestConfiguration.java

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyServiceTestApplication.class)
@ActiveProfiles("test")
public abstract class TestConfiguration {

}

调试时发现myRepository为null,寻求解决帮助。


问题原因及修复步骤

1. 移除数据源自动配置的排除

MyServiceTestApplication中排除了DataSourceAutoConfiguration,导致Spring无法自动配置数据库连接,JPA Repository无法被实例化。修改后的代码:

@SpringBootApplication
public class MyServiceTestApplication {
}

2. 修正测试类的Bean注入方式

测试类已继承TestConfiguration(已加载Spring上下文),无需使用@InjectMocks,直接通过@Autowired注入MyService,Spring会自动注入其依赖MyRepository:

public class MyServiceTest extends TestConfiguration {

    @Autowired
    private MyService myService;

    @Test
    public void mainFunctionTest() {
        myService.mainFunction();
    }
}

3. 调整MyService的访问修饰符

当前MyService是包私有(默认修饰符),若测试类不在同一包下,Spring无法扫描并创建Bean。改为public:

@Component
public class MyService {
    @Autowired 
    private MyRepository myRepository;
    
    public void mainFunction() {
        myRepository.saveSomething();
    }
}

4. 修正Repository的泛型参数

MyRepository的泛型<T, Long>需替换为实际实体类,例如实体类为MyEntity时:

@Repository
public interface MyRepository extends JpaRepository<MyEntity, Long> {
    void saveSomething();
}

5. 正确配置Testcontainers依赖

确保项目中引入Testcontainers的JUnit4及MySQL依赖(以Maven为例):

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>mysql</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>junit4</artifactId>
    <scope>test</scope>
</dependency>

6. 移除手动创建的MySQLContainer

Spring Boot Test会自动识别application-test.properties中的tc:前缀数据源,自动启动Testcontainers容器,无需手动通过@Rule初始化,删除测试类中的@Rule及MySQLContainer实例。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 14:09:07