我有测试代码,我想在其中读取consul的配置。application.properties(src / main / resources)启用consul配置。我有一个POJO类名DBConfig(在src / main / java中),它从领事那里获取配置。我已经在测试类中自动连接了DBConfig,并且当我运行单元测试时,它给了我nullpointerexception,因为它没有从领事那里获取值。 如何处理情况。请帮忙。
@Configuration
@ConfigurationProperties(prefix="db")
@RefreshScope
public class DBConfig {
private String jdbcURL;
private String username;
private String password;
private String driverClass;
...getter setters.
}
测试类---
@RunWith(MockitoJUnitRunner.class)
@Transactional(propagation=Propagation.REQUIRED,readOnly=false,rollbackFor=Exception.class)
@SpringBootTest(classes={DBConfig.class})
public class TestUserDao extends DBTestCase {
@Autowired
private DBConfig dbConfig;
protected final Resource res = new ClassPathResource("actualDataSet.xml");
@Bean
@Profile("test")
@RefreshScope
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(dbConfig.getDriverClass());
dataSource.setUrl(dbConfig.getJdbcURL());
dataSource.setUsername(dbConfig.getUsername());
dataSource.setPassword(dbConfig.getPassword());
return dataSource;
}
@Bean
@Autowired
public NamedParameterJdbcTemplate jdbcTemplate(DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
@Bean
@Autowired
public UserDAO userDAO(NamedParameterJdbcTemplate jdbcTemplate) {
return new UserDAO(jdbcTemplate);
}
@Override
protected IDataSet getDataSet() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
String file = classLoader.getResource("actualDataSet.xml").getFile();
return new FlatXmlDataSetBuilder().build(new FileInputStream(file));
}
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.REFRESH;
}
@Test
public void insertTodo() throws Exception {
}
protected DatabaseOperation getTearDownOperation() throws Exception {
return DatabaseOperation.DELETE;
}
答案 0 :(得分:0)
这可能是由于使用MockitoJUnitRunner
类引起的,该类在启动时不会加载ApplicationContext
,这意味着将无法访问您的bean。
一旦您将在SpringRunner
批注中使用@RunWith()
类,Spring应该能够注入DBConfig
bean。