【发布时间】:2019-06-04 08:20:34
【问题描述】:
我一直在尝试在我的测试类中使用配置属性,但找不到这样做的方法,因为我总是得到 NullPointerException。
应用程序.yaml
affix:
lover: 'interests'
social: 'social_media'
YamlConfig.java
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
@EnableAutoConfiguration
@Data
public class YamlConfig {
private HashMap<String, String> affix;
}
Service.java
@Autowired
private YamlConfig config;
...
setFeatureName(config.getAffix().get("social"));
// supposed to return social_media
上面的代码在我的服务中运行良好,但是当我尝试在我的测试类中使用配置属性时,它不起作用。
ServiceTest.java
@RunWith(MockitoJUnitRunner.class)
public class MetadataServiceTest {
@Autowired
private YamlConfig config;
@Test
public void testPropertiesNotNull() {
assertNotNull(config.getAffix().get("social"));
}
我也尝试了其他注释,但它们似乎都不起作用。大多数示例都使用 JUnitRunner 运行测试,我不确定这是否是它们无法在我的测试类上运行的原因。
有没有办法在不模拟整个事情的情况下使用 MockitoJUnitRunner 在测试类中使用配置属性(实际配置非常大,很难模拟每个结果)?
【问题讨论】:
-
你没有在 spring 上下文中开始你的测试,因此
@Autowired没有被选中,所以没有注入任何东西。使用模拟或弹簧,不要将它们混合使用。 (我建议模拟)
标签: java spring spring-boot mockito