Back-End (web)
[Spring] GatewayFilterFactory Unit Test
햄과함께
2020. 7. 2. 09:17
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())
}
}
320x100