@@ -7,6 +7,7 @@ import assertk.assertions.isNotNull
7
7
import assertk.assertions.isNullOrEmpty
8
8
import assertk.assertions.isTrue
9
9
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent
10
+ import com.google.common.net.MediaType
10
11
import io.mockk.mockk
11
12
import io.moia.router.Router.Companion.router
12
13
import org.junit.jupiter.api.Assertions.assertEquals
@@ -383,6 +384,26 @@ class RequestHandlerTest {
383
384
assertEquals(" {\" message\" :\" Could not find path parameter 'foo\" ,\" code\" :\" INTERNAL_SERVER_ERROR\" ,\" details\" :{}}" , response.body)
384
385
}
385
386
387
+ @Test
388
+ fun `Handler should return the content type that is accepted` () {
389
+ val jsonResponse = AcceptTypeDependingHandler ().handleRequest(
390
+ GET (" /all-objects" )
391
+ .withHeader(" accept" , " application/json" ),
392
+ mockk()
393
+ )
394
+ assertEquals(200 , jsonResponse.statusCode)
395
+ assertEquals(" application/json" , jsonResponse.getHeaderCaseInsensitive(" content-type" ))
396
+ assertEquals(" [{\" text\" :\" foo\" ,\" number\" :1},{\" text\" :\" bar\" ,\" number\" :2}]" , jsonResponse.body)
397
+ val plainTextResponse = AcceptTypeDependingHandler ().handleRequest(
398
+ GET (" /all-objects" )
399
+ .withHeader(" accept" , " text/plain" ),
400
+ mockk()
401
+ )
402
+ assertEquals(200 , plainTextResponse.statusCode)
403
+ assertEquals(" text/plain" , plainTextResponse.getHeaderCaseInsensitive(" content-type" ))
404
+ assertEquals(" [CustomObject(text=foo, number=1), CustomObject(text=bar, number=2)]" , plainTextResponse.body)
405
+ }
406
+
386
407
class TestRequestHandlerAuthorization : RequestHandler () {
387
408
override val router = router {
388
409
GET (" /some" ) { _: Request <Unit > ->
@@ -508,4 +529,33 @@ class RequestHandlerTest {
508
529
}
509
530
}
510
531
}
511
- }
532
+
533
+ class AcceptTypeDependingHandler : RequestHandler () {
534
+
535
+ data class CustomObject (val text : String , val number : Int )
536
+
537
+ class PlainTextSerializationHandler : SerializationHandler {
538
+ override fun supports (acceptHeader : MediaType , body : Any ): Boolean {
539
+ return acceptHeader.`is `(MediaType .parse(" text/plain" ))
540
+ }
541
+
542
+ override fun serialize (acceptHeader : MediaType , body : Any ): String {
543
+ return body.toString()
544
+ }
545
+ }
546
+
547
+ override fun serializationHandlers () =
548
+ listOf (JsonSerializationHandler (objectMapper), PlainTextSerializationHandler ())
549
+
550
+ override fun deserializationHandlers () =
551
+ listOf (JsonDeserializationHandler (objectMapper))
552
+
553
+ override val router = router {
554
+ defaultConsuming = setOf (" application/json" , " text/plain" )
555
+ defaultProducing = setOf (" application/json" , " text/plain" )
556
+ GET (" /all-objects" ) { _: Request <Unit > ->
557
+ ResponseEntity .ok(body = listOf (CustomObject (" foo" , 1 ), CustomObject (" bar" , 2 )))
558
+ }
559
+ }
560
+ }
561
+ }
0 commit comments