Reputation: 29
I am working on a spring api gateway. There is a class LoggingMethods
which i want to test.
It contains two methods appendBodyRequest
and logRequestNoBody
.
Public class LoggingMethods{
LoggingMethods(ServerHttpRequest request){
}
void appendBodyrequest(ByteBuffer byteBuffer , ServerHttpRequest request){
Log.info("Headers:[{}] , Body:[{}]" , request.getHeaders().toSingleValueMap(),
StandardCharsets.UTF_8.decode(byteBuffer));
}
void logRequestNoBody(ServerHttpRequest request){
Log.info("{} response has no body.",request.getMethod());
}
}
I am not sure how to implement unit testing with JUnit with mock headers and body. Appreciate your help and suggestions! Thanks.
Upvotes: 0
Views: 7519
Reputation: 535
One of the approach is to implement ServerHttpRequest in your test method by yourself. It may look like this:
@Test
void testLogRequestNoBody() {
ServerHttpRequest request = new ServerHttpRequest() {
@Override
public InputStream getBody() throws IOException {
return null;
}
...
@Override
public HttpHeaders getHeaders() {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("test", "test");
return httpHeaders;
}
};
LoggingMethods loggingMethods = new LoggingMethods(request);
loggingMethods.logRequestNoBody(request);
}
You can specify the headers you need to test inside implemented method. You can implement remained ServerHttpRequest methods by returning null
.
You don't need Mockito at all in this case. Using Mockito won't give any profit for that purpose.
Upvotes: 1