我想用配置类配置 Spring 假装,我想确保在 Spring 为我配置 feign 客户端时调用所有@Bean
方法。
如何测试?
例如,我有:
@FeignClient(
name = "PreAuthSendRequest",
url = "${xxx.services.preauth.send.url}",
configuration = AppFeignConfig.class)
public interface RequestService {
@PostMapping("")
@Headers("Content-Type: application/json")
PreAuthResponse execute(@RequestBody PreAuthRequest preAuthRequest);
}
和AppFeignConfig.java
:
@Configuration
@RequiredArgsConstructor
public class AppFeignConfig{
private final HttpClient httpClient;
private final Jackson2ObjectMapperBuilder contextObjectMapperBuilder;
@Bean
public ApacheHttpClient client() {
return new ApacheHttpClient(httpClient);
}
@Bean
public Decoder feignDecoder() {
return new JacksonDecoder((ObjectMapper)contextObjectMapperBuilder.build());
}
@Bean
public Encoder feignEncoder() {
return new JacksonEncoder((ObjectMapper)contextObjectMapperBuilder.build());
}
@Bean
public Retryer retryer() {
return Retryer.NEVER_RETRY;
}
@Bean
public ErrorDecoder errorDecoder() {
return new ServiceResponseErrorDecoder();
}
}
那么,如何验证是否调用了所有@Bean
方法呢?我知道@MockBean
,但我要检查的是config.feignDecoder()
等,确实叫。
当我尝试context.getBean(RequestService.class);
并调用execute()
方法时,它似乎发送了一个真正的请求,并且没有 wiremock,显然它会失败。
现在我有这个:
@SpringBootTest
@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
class RequestServiceTest {
@Autowired
private ApplicationContext applicationContext;
@MockBean
private ApacheHttpClient client;
@MockBean
private Decoder feignDecoder;
@MockBean
private Encoder feignEncoder;
@MockBean
private Retryer retryer;
@MockBean
private ErrorDecoder errorDecoder;
@Test
void shouldRetrieveBeansFromApplicationContextToConstructConfigurationInstance() {
AppFeignConfig config = applicationContext.getBean(AppFeignConfig.class);
Assertions.assertEquals(config.feignEncoder(), feignEncoder);
Assertions.assertEquals(config.feignDecoder(), feignDecoder);
Assertions.assertEquals(config.errorDecoder(), errorDecoder);
Assertions.assertEquals(config.client(), client);
Assertions.assertEquals(config.retryer(), retryer);
}
}
我不知道这是不是应该的。如果有任何想法,请发表评论。