Spring Feign配置:如何测试所有@Bean方法都被调用

时间:2019-07-01 13:04:05

标签: java spring mocking spring-cloud-feign

我想使用配置类来配置Spring feign,并且我想确保在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,显然失败了。

1 个答案:

答案 0 :(得分:-1)

现在我有这个:

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

}

我不知道应该怎么做。如果有任何想法,请发表评论。