所以我有一个发出 rest api 请求的应用程序,我添加了 bean 注释如下
@Service
public class RequestService {
@Autowired
RestTemplate restTemplate;
@Autowired
JwtService jwtService;
@Bean
List<String> getInvalidProduct() {
String jwt_access_token = this.jwtService.requestToken();
URI uri = new URI("https://localhost:8080");
ResponseEntity<?> response = this.restTemplate.exchange(uri, HttpMethod.GET, this.jwtService.helper(jwt_access_token), Product[].class);
return response.getBody();
}
}
到目前为止一切正常。 但是,我无法进行 spock 测试。由于这会在应用程序运行后立即注册,添加此代码块后,它会破坏我之前所有的 spock 测试,这是完全可以理解的。
不运行
jwtService.requestToken()
或this.restTemplate.exchange()
,我如何模拟这个bean并注入List<String>
对象?提前非常感谢
我正在尝试如下进行配置类或 spocks 测试
@Configuration
class TestConfiguration {
@SpringBean
List<String> getInvalidProduct() {
List<String> invalids = new ArrayList();
invalids.add("AAA");
invalids.add("BBB");
invalids.add("CCC");
return invalids;
}
}
有没有办法替换这样的豆子?
如果你不想执行服务类中的逻辑
RequestService
,你可以简单地在每个测试类中为它创建模拟bean
class TestSpec extends Specification {
@SpringBean
RequestService requestService = Mock(RequestService.class)
}
或者,如果您希望执行该逻辑但要跳过
jwtService.requestToken()
和 this.restTemplate.exchange()
,那么您可以在每个测试类中为模拟 bean 添加存根
class TestSpec extends Specification {
@SpringBean
RestTemplate restTemplate = Mock(RestTemplate.class)
@SpringBean
JwtService jwtService = Mock(JwtService.class)
def setup() {
//create stub here
jwtService.requestToken() >> "token"
//we can also check for matching input arguments and return the response
restTemplate.exchange(_,_,_,_,_) >> return response body
}
}