如何从测试用例中的属性文件中获取值

how to get the values from properties file in the test cases

我在执行测试用例时从 .properties 文件读取值时得到空值。在这里调试测试用例时,当光标在测试 class 中时,我能够看到从属性文件加载的值,但是当光标进入 class 中的实际 class 时=] 我得到与 null 相同的值。而我的代码如下

提前致谢

@RestController
@PropertySource("classpath:/com/example/prop.properties")
public class ReadProp {
    @Value("${name}")
    private String name;
    @Value("${rollNo}")
    private String rollNo;
    @RequestMapping(value="/")
    public void getDetails(){
        System.out.println(name);
        System.out.println(rollNo);
    }
}
and the test case is as follows

@RunWith(SpringRunner.class)
@SpringBootTest
@PropertySource("classpath:/com/example/prop.properties")
public class ReadPropTest {
    private ReadProp readProp = new ReadProp();
    @Value("${name}")
    private String name;
    @Value("${rollNo}")
    private String rollNo;
    @Test
    public void readValues() {
        System.out.println(name);
        System.out.println(rollNo);
        readProp.getDetails();


    }

}

而不是使用 new ReadProp() 创建新对象。你应该自动装配它。
@Autowired ReadProp readProp;
在你的测试中 class。如果您使用 new 创建对象,则不会获得 spring 使用 @Value.

分配的所有值创建的 bean

尝试这样的事情:

@PropertySource("classpath:prop.properties")// your error
public class ReadPropTest {
   @Value("${name}")
   private String name;
   @Value("${rollNo}")
   private String rollNo;
}