class 中的 Spock 模拟字符串值

Spock Mock String value in class

我正在使用 Spring 并且我想使用 Spock 创建单元测试。这是我的 class

@Service
public class TestService{
    @Value("${test.path:}")
   private String path;
}

是否可以在不运行 spring 上下文的情况下在 Spock 测试中模拟此变量?

考虑到您不想设置 Spring(Boot) 测试,请使用构造函数注入来注入值字段:

@Service
public class TestService{
   private String path;

   public TestService(@Value("${test.path:}") String path) {
        this.path = path;
   }
}
...

TestService service = new TestService("testValue");

或使用 ReflectionTestUtils 设置值:

TestService service = new TestService();
ReflectionTestUtils.setField(service, "path", "somePath");