spock模拟字符串值

1cosmwyk  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(486)

我使用的是spring,我想用spock创建单元测试。这是我的课

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

有没有办法在spock测试中模拟这个变量而不运行spring上下文?

ikfrs5lh

ikfrs5lh1#

考虑到您不想设置spring(boot)测试,可以使用构造函数注入来注入value字段:

@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");

相关问题