在Junit测试中从应用程序属性访问属性时出现空指针异常

问题描述

我有一种方法可以从application.properties访问属性,并且我正在为此编写junit。

class ServiceClass{

@Value("${urlfromapplicationproperties}")
public String myUrl ;

public String getUrl(){
 return myUrl;
}
}

下面是测试用例:

@RunWith(SpringJunit4ClassRunner.class)
@PropertySource("classpath:test:properties")
public class ServiceClassTest {

@Mock 
ServiceClass serviceclass;

@Before
public void setup(){ MockitoAnnotations.initMocks(this);}

@Test
public myTestMethod(){

serviceclass.getUrl();
}
}

当我访问该方法的抛出空指针时。我也在application-test.yml中声明了该属性。我想念什么?任何参考或答案来解决这个问题?

解决方法

您可以使用ReflectionTestUtils setField

@Before
public void setup(){
    ReflectionTestUtils.setField(serviceclass,"myUrl","http://testurl");
    MockitoAnnotations.initMocks(this);}
}
,

ServiceClass应该定义为Spring bean

@Configuration    
public class ServiceClass {

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...