Java Spring - 如何使用来自 application.properties 的值和 @WithUserDetails

Java Spring - How to use value from application.properties with @WithUserDetails

我想将 application.properties 中的值与 @WithUserDetails() 注释一起用于我的测试。

我当前的代码:

@Value("${user.admin}")
private String ADMIN;

@Test
@WithUserDetails(ADMIN)
public void foo() { 
}

显示错误"Attribute value must be constant"

我将 junit4 与 spring runner

一起使用

java 具有读取 .properties 文件的内置功能,JUnit 具有在执行测试套件之前 运行 设置代码的内置功能。

java阅读属性:

Properties p = new Properties();
p.load(new FileReader(new File("application.properties")));

junit startup documentation

把这两个放在一起,你应该就有你需要的了。

但是是的,最低要求是您的 test->resources 包中也有 application.properties 文件。

这似乎无法完成,Java 编译器不允许这样做,因为它在编译时不认为来自 @Value() 的值是常量。