问题描述
我有一种方法可以从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 {