java - How to mock a spring bean? -
i'm trying mock class uses jaxrs , class spring component.
@component public class postmanclient { private webtarget target; public postmanclient() { client client = clientbuilder.newclient(); target = client.target(...); } public string send(string xml) { builder requestbuilder = target.request(mediatype.application_xml_type); response response = requestbuilder.post(entity.entity(xml, mediatype.application_xml_type)); homecoming response.readentity(string.class); } } this test method:
@test public void processpendingregisterswithautomaticsyncjob() throws exception { postmanclient postmanclient = mock(postmanclient.class); string response = "ok"; whennew(postmanclient.class).withnoarguments().thenreturn(postmanclient); when(postmanclient.send("blablabla")).thenreturn(response); loadapplicationcontext(); // applicationcontext = new classpathxmlapplicationcontext("/test-context.xml"); } when debug postmanclient instance, instance created spring , not mock. how can avoid behavior , mock instance ?
if using powermock spring, should consider next tips: 1. utilize @runwith(springjunit4runner.class) 2. utilize @contextconfiguration("/test-context.xml") // load spring context before test 3. utilize @preparefortest(....class) // mock static method 4. utilize powermockrule 5. simplest way mock spring bean utilize springockito
back question: if don't understand wrong, have postmanclient defined in spring context, means, need utilize springockito accomplish goal, follow tutorial on springockito page.
java spring unit-testing mockito powermock
No comments:
Post a Comment