How to make a JUnit test for a handler

2,502 views
Skip to first unread message

Fernando Jordán Silva

unread,
Nov 22, 2013, 7:52:28 AM11/22/13
to ve...@googlegroups.com
Just a simple question: how can I make a unit test (not integration) of a Handler class ?

Example code: 
public void handle(final HttpServerRequest request) {
    request.bodyHandler(new Handler<Buffer>() {
        @Override
        public void handle(Buffer buffer) {
            // Code to test
        }
    });
}

Joern Bernhardt

unread,
Nov 22, 2013, 8:07:40 AM11/22/13
to ve...@googlegroups.com
Create a class for the Handler:

class HttpServerRequestBodyHandler extends Handler<Buffer> {

  @Override
  public void handle(Buffer buffer) {
    ...
  }
}

... and test it by calling theHandler.handle(yourUnitTestBuffer); ?

Fernando Jordán Silva

unread,
Nov 22, 2013, 4:15:55 PM11/22/13
to ve...@googlegroups.com
Yes, that's right for simple objects like Buffer but if the handler is this:

@Override
public void handle(final HttpServerRequest request) {
    // code to test
}

How can I test it ? 

Joern Bernhardt

unread,
Nov 22, 2013, 5:09:17 PM11/22/13
to ve...@googlegroups.com
If you really don't want to do integration tests for things like that, I guess you need to mock the HttpServerRequest with something like Mockito. I'm not aware of a better way right now, because of that we're testing our modules mostly via integration tests.

Stream Liu

unread,
Nov 22, 2013, 6:29:19 PM11/22/13
to ve...@googlegroups.com

Yes, you may need a mock, but you can use vert.x API directly,
such as create http server in your test.
you could learn more from test case of Vert.x
--
Stream Liu

Blog: www.streamis.me

松节油

unread,
Nov 23, 2013, 6:08:38 AM11/23/13
to ve...@googlegroups.com
I use Mockito. use a mocked HttpServerRequest,  custom Answer for bodyHandler to save the handler object, then call it.

like this:

mockRequst = mock(HttpServerRequest.class);

doAnswer(new Answer() {
    public Object answer(InvocationOnMock invocation) {
        Object[] args = invocation.getArguments();

        parentClass.this.saveHandler(args[0]);    //save handler
        Mock mock = invocation.getMock();
        return null;
    }
}).when(
mockRequst).bodyHandler(any(Handler.class));

handle(mockRequest);

//test
this.getHandler().handle(mockBuffer);

在 2013年11月22日星期五UTC+8下午8时52分28秒,Fernando Jordán Silva写道:
Reply all
Reply to author
Forward
0 new messages