Netfilix Feign Client 테스트하는 방법이다.

 

github이슈에도 몇개 등록이 되어있는데 자세하게 읽어보지는 않았다.

 

 

 

 

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;

@FeignClient(name = "authentication-service")
public interface AuthServiceClient {

    @PostMapping("/authenticate")
    Member getMember(String accessToken);

}

 

    @MockBean
    AuthServiceClient authServiceClient;
    
    
    
    ...
    
    
        @Test
        public void access_auth_user() throws Exception {
        
        
        ...
        
        
        Mockito.when(authServiceClient.getMember(accessToken)).thenReturn(member);

        ...
    }

 

일반적으로 Feign Client를 다음과같이 mocking하면 mock객체가아니라 실제 feign 구현체가 들어가서 테스트에 실패한다.

 

feign client를 mocking하는 방법은 아래와 같다

 

 

 

//primary 옵션을 false로 설정
@FeignClient(name = "authentication-service", primary = false)
public interface AuthServiceClient {

    @PostMapping("/authenticate")
    Member getMember(String accessToken);

}

 

    
    //test에서 선언시 name속성 추가
    @MockBean(name = "authServiceClient")
    AuthServiceClient authServiceClient;

 

 

이런식으로 테스트를 하면 mocking된 객체가 들어간다.

 

 

 

 

 

 

 

 

https://github.com/spring-cloud/spring-cloud-openfeign/issues/336

 

MockBean behaviour for Feign Clients change since Spring Boot 2.2.7 Release · Issue #336 · spring-cloud/spring-cloud-openfeign

Bug Versions: Spring Boot: 2.2.7 Spring Cloud: Hoxton.SR4 Before the Spring Boot 2.2.7 release, we used to create a Feign client (no fallback needed) and in certain situations we needed to create a...

github.com

 

 

 

 

 

----추가

 

추가적으로 슬라이스 테스트할때 Feign Client 객체를 autowired받는 방법이다.

@RestClientTest(MemberServiceClient.class)
@Import({RibbonAutoConfiguration.class,
        FeignRibbonClientAutoConfiguration.class,
        FeignAutoConfiguration.class})
class MemberServiceClientTest {

    @Autowired
    private MemberServiceClient client;
    
  
    //...tests  
  
  
}

 

https://github.com/spring-projects/spring-boot/issues/7270

 

+ Recent posts