我使用的是spring,我想用spock创建单元测试。这是我的课
@Servicepublic class TestService{ @Value("${test.path:}") private String path;}
@Service
public class TestService{
@Value("${test.path:}")
private String path;
}
有没有办法在spock测试中模拟这个变量而不运行spring上下文?
ikfrs5lh1#
考虑到您不想设置spring(boot)测试,可以使用构造函数注入来注入value字段:
@Servicepublic class TestService{ private String path; public TestService(@Value("${test.path:}") String path) { this.path = path; }}...TestService service = new TestService("testValue");
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");
TestService service = new TestService();
ReflectionTestUtils.setField(service, "path", "somePath");
1条答案
按热度按时间ikfrs5lh1#
考虑到您不想设置spring(boot)测试,可以使用构造函数注入来注入value字段:
或使用reflectiontestutils设置值: