본문 바로가기
Back-End (web)

[Spring] GatewayFilterFactory Unit Test

by 햄과함께 2020. 7. 2.
320x100

kotlin 으로 작성되었습니다.

@Component
class CustomGatewayFilterFactory : AbstractGatewayFilterFactory<Any>() {

    override fun apply(config: Any?) = GatewayFilter { exchange: ServerWebExchange, chain: GatewayFilterChain ->
        var request = exchange.request
        val value = request.headers["My-Header"]?.firstOrNull()

        request = request.mutate()
            .headers { it.add("Test-Header", AbstractGatewayFilterFactory) }
            .build()

        chain.filter(exchange.mutate().request(request).build())
    }
}

 My-Header 에 있는 값을  Test-Header  value로 추가하는 필터

@ExtendWith(MockKExtension::class)
class CustomGatewayFilterFactoryTest {

    private lateinit var filterFactory: CustomGatewayFilterFactory

    @BeforeEach
    fun setup() {
        filterFactory = CustomGatewayFilterFactory()
    }

    @Test
    fun `custom filter 테스트`() {
        // given
        val value = "test"
        val exchange = MockServerWebExchange.from(
            MockServerHttpRequest.get("/test")
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .header("My-Header", value)
                .build()
        )
        val chain = mockk<GatewayFilterChain>()

        // mock
        every { chain.filter(any()) } returns Mono.empty()

        // when
        val filter = filterFactory.apply(mockk(relaxed = true))
        filter.filter(exchange, chain)

        // then
        assertEquals(value, exchange.request.headers["Test-Header"]?.firstOrNull())
    }
}

 

참고 : https://www.programcreek.com/java-api-examples/?code=spring-cloud%2Fspring-cloud-gateway%2Fspring-cloud-gateway-master%2Fspring-cloud-gateway-core%2Fsrc%2Ftest%2Fjava%2Forg%2Fspringframework%2Fcloud%2Fgateway%2Ffilter%2Ffactory%2FRewritePathGatewayFilterFactoryTests.java

320x100

댓글