【问题标题】:Null pointer exception while accessing property from application properties in Junit test在 Junit 测试中从应用程序属性访问属性时出现空指针异常
【发布时间】:2021-01-06 21:17:35
【问题描述】:

我有从 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 中声明了该属性。我错过了什么?任何参考或答案来解决这个问题?

【问题讨论】:

标签: java spring-boot junit junit4 spring-boot-test


【解决方案1】:

ServiceClass 应该定义为 Spring bean

@Configuration    
public class ServiceClass {

【讨论】:

    【解决方案2】:

    你可以使用ReflectionTestUtilssetField

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-23
      • 2012-05-13
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多