There is an interface:
interface IEventListener
{
void onEvent(List <IEvent> events);
}
There is an event class:
class EventB
{
private final int id;
private final A a;
private final String somethingElse;
...
// constructors, getters
...
}
And there is a class to test:
class Doer
{
IEventListener eventListener;
void doSomething(Aaa a)
{
eventListener.onEvent(Arrays.asList(new EventA(1), new EventC(2)));
...
eventListener.onEvent(Arrays.asList(new EventB(42, a.getA(), "foo"), new EventA(3), new EventB(0, a.getA(), "bar")));
...
eventListener.onEvent(Arrays.asList(new EventC(4)));
}
}
The Doer is a code which I need to test, the method doSomething produces packs of events, and I need to test if it produces a particular event in some specific conditions.
More precisely I want to have a unit test which calls the method doSomething and checks that EventB is sent with “42” and A as from method argument a. All other events should be ignored.
To make such test I’ve only came up with solution involving quite verbose code with ArgumentCaptor, for-blocks, and magic boolean flags…
What is the best way to make a unit test for it? Maybe the code design is bad?
The design is correct, this is how you test it with Mockito:
It’s Mockito 1.9.0 and Hamcrest-library 1.2.1.
To use JUnit 4.10 together with Hamcrest-library 1.2.1 you should use
junit:junit-dep:4.10artifact, and excludeorg.hamcrest:hamcrest-corefrom it: