从 Junit 测试中的应用程序属性访问 属性 时出现空指针异常
Null pointer exception while accessing property from application properties in Junit test
我有从 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 {
我有从 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 {