空指针异常,在 JUnit 测试中访问应用程序属性时发生

huangapple go评论83阅读模式
英文:

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

以下是您要翻译的内容:

您可以使用ReflectionTestUtilssetField方法:

@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 {

huangapple
  • 本文由 发表于 2020年9月21日 00:14:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63981068.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定