Skip to content

Commit 1977fe2

Browse files
tamasradumaibin
authored andcommitted
BAEL-1372: Adding jUnits for Testing Netty with EmbeddedChannel article (eugenp#3973)
1 parent c2034ca commit 1977fe2

4 files changed

Lines changed: 245 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.baeldung.netty;
2+
3+
import io.netty.buffer.ByteBuf;
4+
import io.netty.buffer.Unpooled;
5+
import io.netty.channel.ChannelHandlerContext;
6+
import io.netty.channel.SimpleChannelInboundHandler;
7+
import io.netty.handler.codec.http.*;
8+
import io.netty.util.CharsetUtil;
9+
10+
public class CalculatorOperationHandler extends SimpleChannelInboundHandler<Operation> {
11+
12+
protected void channelRead0(ChannelHandlerContext ctx, Operation msg) throws Exception {
13+
Long result = calculateEndpoint(msg);
14+
sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CREATED), result.toString());
15+
ctx.fireChannelRead(result);
16+
}
17+
18+
private long calculateEndpoint(Operation operation) {
19+
20+
String operator = operation.getOperator().toLowerCase().trim();
21+
switch (operator) {
22+
case "add":
23+
return operation.getNumber1() + operation.getNumber2();
24+
case "multiply":
25+
return operation.getNumber1() * operation.getNumber2();
26+
default:
27+
throw new IllegalArgumentException("Operation not defined");
28+
}
29+
}
30+
31+
public static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpResponse res, String content) {
32+
33+
// Generate an error page if response getStatus code is not OK (200).
34+
ByteBuf buf = Unpooled.copiedBuffer(content, CharsetUtil.UTF_8);
35+
res.content().writeBytes(buf);
36+
37+
HttpUtil.setContentLength(res, res.content().readableBytes());
38+
39+
ctx.channel().writeAndFlush(res);
40+
}
41+
42+
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
43+
throws Exception {
44+
45+
sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR), "Operation not defined");
46+
ctx.fireExceptionCaught(cause);
47+
}
48+
49+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.baeldung.netty;
2+
3+
import io.netty.channel.ChannelHandlerContext;
4+
import io.netty.channel.SimpleChannelInboundHandler;
5+
import io.netty.handler.codec.http.FullHttpRequest;
6+
import io.netty.handler.codec.http.HttpHeaders;
7+
import io.netty.handler.codec.http.HttpMethod;
8+
9+
public class HttpMessageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
10+
11+
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
12+
13+
String uri = msg.uri();
14+
HttpMethod httpMethod = msg.method();
15+
HttpHeaders headers = msg.headers();
16+
17+
if (HttpMethod.GET == httpMethod) {
18+
19+
String[] uriComponents = uri.split("[?]");
20+
String endpoint = uriComponents[0];
21+
String[] queryParams = uriComponents[1].split("&");
22+
23+
if ("/calculate".equalsIgnoreCase(endpoint)) {
24+
25+
String[] firstQueryParam = queryParams[0].split("=");
26+
String[] secondQueryParam = queryParams[1].split("=");
27+
28+
Integer a = Integer.valueOf(firstQueryParam[1]);
29+
Integer b = Integer.valueOf(secondQueryParam[1]);
30+
String operator = headers.get("operator");
31+
32+
Operation operation = new Operation(a, b, operator);
33+
ctx.fireChannelRead(operation);
34+
}
35+
} else {
36+
throw new UnsupportedOperationException("HTTP method not supported");
37+
}
38+
39+
}
40+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.baeldung.netty;
2+
3+
import java.io.Serializable;
4+
5+
public class Operation implements Serializable {
6+
7+
private Integer number1;
8+
private Integer number2;
9+
private String operator;
10+
11+
public Operation(Integer number1, Integer number2, String operator) {
12+
this.number1 = number1;
13+
this.number2 = number2;
14+
this.operator = operator;
15+
}
16+
17+
public Integer getNumber1() {
18+
return number1;
19+
}
20+
21+
public void setNumber1(Integer number1) {
22+
this.number1 = number1;
23+
}
24+
25+
public Integer getNumber2() {
26+
return number2;
27+
}
28+
29+
public void setNumber2(Integer number2) {
30+
this.number2 = number2;
31+
}
32+
33+
public String getOperator() {
34+
return operator;
35+
}
36+
37+
public void setOperator(String operator) {
38+
this.operator = operator;
39+
}
40+
41+
@Override
42+
public String toString() {
43+
return "Operation{" +
44+
"number1=" + number1 +
45+
", number2=" + number2 +
46+
", operator='" + operator + '\'' +
47+
'}';
48+
}
49+
}
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package com.baeldung.netty;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.assertTrue;
5+
6+
import java.nio.charset.Charset;
7+
8+
import org.junit.Assert;
9+
import org.junit.Test;
10+
11+
import io.netty.channel.embedded.EmbeddedChannel;
12+
import io.netty.handler.codec.http.DefaultFullHttpRequest;
13+
import io.netty.handler.codec.http.FullHttpRequest;
14+
import io.netty.handler.codec.http.FullHttpResponse;
15+
import io.netty.handler.codec.http.HttpMethod;
16+
import io.netty.handler.codec.http.HttpResponseStatus;
17+
import io.netty.handler.codec.http.HttpVersion;
18+
19+
public class EmbeddedChannelUnitTest {
20+
21+
@Test
22+
public void givenTwoChannelHandlers_testPipeline() {
23+
24+
final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/calculate?a=10&b=5");
25+
httpRequest.headers().add("Operator", "Add");
26+
27+
EmbeddedChannel channel = new EmbeddedChannel(
28+
new HttpMessageHandler(), new CalculatorOperationHandler());
29+
30+
channel.pipeline()
31+
.addFirst(new HttpMessageHandler())
32+
.addLast(new CalculatorOperationHandler());
33+
34+
35+
// send HTTP request to server and check that the message is on the inbound pipeline
36+
assertTrue(channel.writeInbound(httpRequest));
37+
38+
long inboundChannelResponse = channel.readInbound();
39+
assertEquals(15, inboundChannelResponse);
40+
41+
// we should have an outbound message in the form of a HTTP response
42+
assertEquals(1, channel.outboundMessages().size());
43+
// Object response = channel.readOutbound();
44+
45+
FullHttpResponse httpResponse = channel.readOutbound();
46+
String httpResponseContent = httpResponse.content().toString(Charset.defaultCharset());
47+
assertTrue("15".equalsIgnoreCase(httpResponseContent));
48+
}
49+
50+
@Test
51+
public void givenTwoChannelHandlers_testExceptionHandlingInHttpMessageHandler() {
52+
53+
EmbeddedChannel channel = new EmbeddedChannel(
54+
new HttpMessageHandler(), new CalculatorOperationHandler());
55+
56+
final FullHttpRequest wrongHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/calculate?a=10&b=5");
57+
wrongHttpRequest.headers().add("Operator", "Add");
58+
59+
try {
60+
// send invalid HTTP request to server and expect and error
61+
channel.pipeline().fireChannelRead(wrongHttpRequest);
62+
channel.checkException();
63+
// channel.writeInbound(wrongHttpRequest);
64+
Assert.fail();
65+
66+
} catch (Exception ex) {
67+
68+
// the HttpMessageHandler does not handle the exception and throws it down the pipeline
69+
assertTrue(ex instanceof UnsupportedOperationException);
70+
assertTrue(ex.getMessage().equalsIgnoreCase("HTTP method not supported"));
71+
72+
FullHttpResponse errorHttpResponse = channel.readOutbound();
73+
String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
74+
assertTrue("Operation not defined".equalsIgnoreCase(errorHttpResponseContent));
75+
assertEquals(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorHttpResponse.status());
76+
}
77+
}
78+
79+
80+
@Test
81+
public void givenTwoChannelHandlers_testExceptionHandlingInCalculatorOperationHandler() {
82+
EmbeddedChannel channel = new EmbeddedChannel(
83+
new HttpMessageHandler(), new CalculatorOperationHandler());
84+
85+
final FullHttpRequest wrongHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/calculate?a=10&b=5");
86+
wrongHttpRequest.headers().add("Operator", "Invalid_operation");
87+
88+
try {
89+
// send invalid HTTP request to server and expect and error
90+
channel.writeInbound(wrongHttpRequest);
91+
Assert.fail();
92+
93+
} catch (Exception ex) {
94+
95+
// the HttpMessageHandler does not handle the exception and throws it down the pipeline
96+
assertTrue(ex instanceof IllegalArgumentException);
97+
assertTrue(ex.getMessage().equalsIgnoreCase("Operation not defined"));
98+
99+
// the outbound message is a HTTP response with the status code 500
100+
FullHttpResponse errorHttpResponse = channel.readOutbound();
101+
String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
102+
assertTrue("Operation not defined".equalsIgnoreCase(errorHttpResponseContent));
103+
assertEquals(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorHttpResponse.status());
104+
}
105+
}
106+
107+
}

0 commit comments

Comments
 (0)