繁体   English   中英

尝试自动装配运行MockitoJUnitRunner的配置属性时发生NullPointerException

[英]NullPointerException when trying to autowire configuration properties running with MockitoJUnitRunner

我一直在尝试在测试类中使用配置属性,但是找不到方法,因为我总是会收到NullPointerException。

application.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被忽略。 使它成为带有注释的集成Spring测试。

由于您使用的是@Autowired批注,因此应使用例如:@RunWith(SpringJUnit4ClassRunner.class)

这样,您将在春季环境中开始测试。

但是,如果您仍然想使用MockitoJUnitRunner,则可以使用@InjectMocks private YamlConfig config来代替@Autowired。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM