junit - Spring Integration Java DSL unit test - How to mock a Service Activator class or other components/endpoints? -
i have class contains few service activator methods follows:
@messageendpoint public class testservice { @serviceactivator public void setcomplete(message<string> message){ //do stuff } }
in integration flow, 1 of channels call 1 of these methods:
@bean public testservice testservice() { return new testservice(); } @bean public integrationflow testflow() { return integrationflows.from("testchannel") .handle("testservice", "setcomplete") .handle(logger()) .get(); }
i'm writing unit test flow , using mockito mcoking service activator class:
@contextconfiguration(classes = integrationconfig.class) @runwith(springjunit4classrunner.class) @dirtiescontext public class apptest { @mock private thegateway startgateway; @mock private testservice testrvice; @autowired @qualifier("testchannel") directchannel testchannel; @before public void setup() { mockitoannotations.initmocks(this); } @test() public void testmessageproducerflow() throws exception { mockito.donothing().when(startgateway).execute("test"); startgateway.execute("test"); mockito.verify(startgateway).execute("test"); testchannel.send(new genericmessage<>("test")); mockito.verify(testservice).setcomplete(new genericmessage<>("test")); } }
when don't mock testservice, executes flow without issues. guideance on how mock service activator class helpful.
update: when mock (as shown in snippet above), not call mocked object, instead executes actual stuff, , last line mockito.verify(testservice)...
asserts mock testservice never called.
first of misunderstood how spring test framework works.
@contextconfiguration(classes = integrationconfig.class)
loads config without modification , start application context based on config.according first condition
.handle("testservice", "setcomplete")
usestestservice()
@bean
not@mock
only after test applicationcontext startup
@mock
s ,@autowired
s start working.
in other words mocking doesn't change in original integrationconfig
.
in framework use reflection retrieve field of particular bean replace mock. isn't easy way.
i suggest distinguish integration , service configuration , use 2 different classes production , testing. this:
the
testservice()
@bean
must movedintegrationconfig
new@configuration
class production.the
testserviceconfig
may this:@bean public testservice testservice() { return mockito.mock(new testservice()); }
and
apptest
should modified this:@contextconfiguration(classes = {integrationconfig.class, testserviceconfig.class}) .... @autowired private testservice testrvice;
that's because application context , unit test scopes on different levels.
Comments
Post a Comment