ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Adaptor 패턴으로 호출가능한 Local 환경 만들기
    Spring Framework 2024. 3. 8. 00:01

    개요

    FeignClient를 활용하다 보면 Local 호출 테스트를 수행하기 위해 MockServer를 띄우는 작업을 수행해야 합니다.

    어떻게 하면 Dummy값으로라도 Local에서도 호출 테스트를 수행해 볼 수 있을까요?

     

    문제 상황

    @FeignClient(
        name = "localTestFeign",
        url = "http://external-service:8080",
        dismiss404 = true,
    )
    interface ExternalServiceCallFeignClient {
        @GetMapping("/external-service-call")
        fun getExternalInformation(): String
    }

    feignClient url을 가상의 외부 도메인을 호출한다고 가정하겠습니다.

     

    @RestController
    class TestController(
            private val externalServiceCallFeignClient: ExternalServiceCallFeignClient,
    ) {
        @GetMapping("/test")
        fun test() = externalServiceCallFeignClient.getExternalInformation()
    }

    이때 Local에서 바로 호출하는 테스트를 수행해보려면 어떻게 될까요?

     

    java.net.ConnectException: Connection refused: no further information

    ConnectException이 발생하게 됩니다.

     

     

    해결방법

    FeignClient 자체를 제어하지 못하기 때문에 Port & Adaptor 패턴으로 호출가능하게 만들 수 있습니다.

     

    interface InformationPort {
    
        fun getInformation(): String
    
        @Component
        @Profile("local")
        class DummyInfomationAdpator: InformationPort {
            override fun getInformation(): String {
                return "DUMMY INFORMATION"
            }
        }
    
        @Component
        @Profile("!local")
        class DefaultInformationAdaptor(
                private val feignClient: ExternalServiceCallFeignClient
        ): InformationPort{
            override fun getInformation(): String{
                return feignClient.getExternalInformation()
            }
        }
    }

    InformationPort를 두고 Adpator 클래스를 통하여 Local 환경에서는 더미값을 제공하고 Local 환경이 아니라면 실제로 FeignClient를 호출하도록 구성합니다.

     

     

    호출결과

    local에서도 호출할 수 있는 환경으로 만들 수 있습니다.

    댓글

Designed by Tistory.