spock模拟字符串值

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

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

  1. @Service
  2. public class TestService{
  3. @Value("${test.path:}")
  4. private String path;
  5. }

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

ikfrs5lh

ikfrs5lh1#

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

  1. @Service
  2. public class TestService{
  3. private String path;
  4. public TestService(@Value("${test.path:}") String path) {
  5. this.path = path;
  6. }
  7. }
  8. ...
  9. TestService service = new TestService("testValue");

或使用reflectiontestutils设置值:

  1. TestService service = new TestService();
  2. ReflectionTestUtils.setField(service, "path", "somePath");
展开查看全部

相关问题