unit testing - Not able to inject mock objects -
unit testing - Not able to inject mock objects -
i newe mockito , junit, have written unit test cases testing rest service , made utilize of mockito injecting mocks. , code below:
billcontrollertest.java:
@runwith(springjunit4classrunner.class) @springapplicationconfiguration(classes = application.class) @webappconfiguration public class billcontrollertest{ private mockmvc mockmvc; @autowired private webapplicationcontext webapplicationcontext; @injectmocks private billcontroller billcontroller; @mock private billservice mockbillservice; @before public void setupcontroller() { mockitoannotations.initmocks(this); this.mockmvc = webappcontextsetup(webapplicationcontext).build(); } @test public void testbills() throws exception { // false info final list<bill> fakebilllist = new arraylist<>(); fakebilllist.add(cpsfake.bill("1234")); when(mockbillservice.getbills(bill_uid)) .thenreturn(fakebilllist.stream()); mockmvc.perform(get("/bills/" + bill_uid )) .andexpect(content().contenttype(mediatypes.hal_json)) // expect particular uid .andexpect(content().string(containsstring("\"uid\":\"1234\"")))
applicationtest.java:
@runwith(springjunit4classrunner.class) @springapplicationconfiguration(classes = application.class) @webappconfiguration public class applicationtest { @test public void contextloads() { } }
billcontroller.java:
@restcontroller @requestmapping(value = "/trials/{billuid}", produces = "application/hal+json") public class billcontroller extends basecontroller { @autowired private billservice billservice; @autowired public billcontroller(billservice billservice) { this.billservice = billservice; } @requestmapping(method = requestmethod.get, value = "") public responseentity<resources<resource<bill>>> getbills(@pathvariable string billuid) { homecoming resourcelistresponseentity( () -> billservice.getbills(billuid), bill-> createresource(bill), resources -> resources.add(linkto(methodon(billcontroller.class) .getbills(billuid)).withselfrel())); }
when run test (billcontrollertest), mockbillservice not getting invoked , instead calling actual billservice. please help me in issue. give thanks in advance.
i think problem utilize mockito spring. both create utilize of proxys.
looking @ code of getbills
- not dependent on spring application context. skip spring setup code (mockmvc
, webapplicationcontext
) , utilize mockito. if yet invisible code depends on applicationcontext - mock application context rather setting real one.
this test be:
simpler container independent fasteryou replace initmocks
annotation runwith(mockitojunitrunner.class)
if want.
unit-testing junit mockito
Comments
Post a Comment