英文:
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 文件中声明了该属性。我漏掉了什么?是否有任何参考或答案可以解决这个问题?
英文:
I have method which access property from application.properties & for which I am writing junit.
class ServiceClass{
@Value("${urlfromapplicationproperties}")
public String myUrl ;
public String getUrl(){
return myUrl;
}
}
Below is test case:
@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();
}
}
when I access the method its throwing null pointer. I have declared that property in application-test.yml too. what I am missing? any reference or answer to resolve this?
答案1
得分: 2
以下是您要翻译的内容:
您可以使用ReflectionTestUtils
的setField方法:
@Before
public void setup(){
ReflectionTestUtils.setField(serviceclass, "myUrl", "http://testurl");
MockitoAnnotations.initMocks(this);
}
英文:
You can use ReflectionTestUtils
setField
@Before
public void setup(){
ReflectionTestUtils.setField(serviceclass, "myUrl", "http://testurl");
MockitoAnnotations.initMocks(this);}
}
答案2
得分: 0
ServiceClass应该被定义为Spring bean。
@Configuration
public class ServiceClass {
英文:
ServiceClass should be define as Spring bean
@Configuration
public class ServiceClass {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论