It's my first time on testing (yes, i've never run a test before, but it's never to late to get started, isn't it?)
I'd a parser that parses a buffer, and dispatch an event).
Calling the parser:
parser.parse((ByteBuffer) readBuffer.duplicate().flip(), key);
parse method:
@Override
public void parse(final ByteBuffer buffer, final SelectionKey key) {
//Parse some stuff here and then dispatch a new event
eventDispatcher.dispatch(new ConnectionDataReadyArgs(key, host.toString(), port));
}
event handler:
@Override
public void handle(final ConnectionDataReadyArgs args) {
//Do stuff here with the recieved args
}
How do I create a junit test that checks if the arguments received on the event handler are right?
Thanks in advance.
One problem with writing tests after writing the code, is that you may not have designed the code for testability.
Dependency injection makes code easier to test. If you're lucky, you're already injecting the eventDispatcher. If not, it would help to make it so, by making the eventDispatcher a constructor parameter:
public MyClass(EventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
}
(You could also use a setter -- but I prefer to make my objects immutable)
Once you've done that, you can inject a test EventDispatcher:
class TestEventDispatcher implements EventDispatcher {
public Event event;
public EventDispatchChain tail;
public Event dispatchEvent(Event event, EventDispatchChain tail) {
this.event = event;
this.tail = tail;
return null;
}
}
TestEventDispatcher testDispatcher = new TestEventDispatcher();
MyClass testObject = new MyClass(testDispatcher);
testObject.dosomething();
assertThat(testDispatcher.event, someMatcher(...));
A mocking framework such as Mockito or JMock provides a dynamic and fluent way of creating mock objects for this purpose. It's better in many ways than creating ad-hoc static test implementations as I've done here. Read the introductory documentation for either of these.
This is for unit testing. You probably also want some integration tests that use a real EventDispatcher along with several of your own objects, checking that when something happens in object A, the eventDispatcher triggers and something happens in object B.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With