Reputation: 135
I have a callback routine that is used to handle Google pubsub messages:
private MessageReceiver getMessageReceiver() {
return (message, consumer) -> {
if (message.getAttributesMap() != null) {
method1();
} else {
method2();
}
};
}
I need to write a junit 4 test to verify which method (1 or 2) is invoked, given a message. I know how to do that for a straighforward method, but not a method that returns a callback. can anyone provide a quick example of how to do that?
Upvotes: 0
Views: 316
Reputation: 4086
So you've got either a structure or conceptual challenge. I'll put it this way, what's your unit under test?
If it's just the callback, i.e. "when callback is called with such and such message, it should call method1", then method1
needs to become part of your test harness. In other words you need to spy on method1
and method2
so you can capture and assert on when they are and are not called. The challenge here is that the more "clever" you get with spies and mocks, the more complicated and brittle your tests are. You may need to separate getMessageReceiver
from the class containing method1
and method2
in this case.
If it's the class containing the getMessageReceiver
, method1
and method2
methods, then you need to invoke the callback and assert on the externalities of method1
and method2
. E.g. if calling method1
invokes someDelegate.doAThing()
, inject a mock of someDelegate
and assert that doAThing
is called.
Upvotes: 3