尝试使用 SpringRunner 进行单元测试时出现 NullPointer 异常



嗨,我正在尝试使用 SpringRunner.class 运行我的单元测试。我正在我的测试类中为 jdbcTemaplte 创建一个新实例。我正在使用 H2 DB 进行单元测试,并且能够使用 jdbcTemplate 实例来创建或更新表。它工作正常。但是当它进入实际类时,它的测试jdbc模板为空,这抛出NullPointerException

下面是代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyClassTest {
@InjectMocks
private ClassToTest classToTest;
@Autowired
private JdbcTemplate jdbcTemplate;
@org.springframework.context.annotation.Configuration
static class Config {
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate orderService() {
        BasicDataSource dataSourceConfig = new BasicDataSource();
        dataSourceConfig.setDriverClassName("org.h2.Driver");
        dataSourceConfig.setUrl("jdbc:h2:mem:db");
        dataSourceConfig.setUsername("someUserName");
        dataSourceConfig.setPassword("somePassword");
        return new JdbcTemplate(dataSourceConfig);
    }
}
@Before
public void setUp() throws Exception {
//Use the jdbcTemplate to create Queries in H2 which works fine.
}
}

类测试.java

 public class ClassToTest{
    @Autowired
    JdbcTemplate jdbcTemplate;
   //someMethod in DAO using jdbcTemplate to make sql Operations.
}

JDBC 模板在 ClassToTest 中为 null,并在尝试测试该方法时抛出 nullPointerException。

只是不确定为什么自动线没有连接我创建的依赖项。我试图在必要时使用@Primary来明确采用这个 jdbcTemplate,但不确定为什么它不起作用。

任何建议在这里都有帮助。提前谢谢。

你在被测试的对象上使用@InjectMocks注释,但你没有嘲笑任何东西,而是想加载 spring 上下文并将 jdbcTemplate bean 注入其中。尝试在 ClassToTest 上将@InjectMocks替换为@Autowired并删除 jdbcTemplate 字段。jdbcTemplate bean 应该在 Config 中初始化,并自动连接到 ClassToTest。此外,您可能希望在@ContextConfiguration中指定 Config 类。希望对您有所帮助。

我看到许多可能导致原因的因素:

  • 你的类"ClassToTest"不是Spring服务/组件,自动连线无法工作。你为什么不用@Component注释它?
  • Spring 建议在构造函数中放置自动线的良好实践。

喜欢:

@Component
public class ClassToTest {
    private JdbcTemplate template;
    @Autowired // Although it's not even required when you have only one constructor : it's by default autowired
    public ClassToTest(JdbcTemplate template) {
        this.template = template;
    }
}

试试这个,告诉我们什么有效。祝你好运

最新更新