i want test class using spring + junit + mockito don't manage make work properly.
let's class references service:
@controller public class mycontroller { @autowired private myservice service; @postconstruct public void init() { service.whatever(); } public void dosomething() { service.create(); } } and service references repository:
@service public class myservice { @autowired private myrepository repository; public void whatever() {} public void create() { repository.save(); } } when testing mycontroller class, want service mocked. problem is: even when service mocked, spring tries inject repository in mock.
here did. test class:
@runwith(springjunit4classrunner.class) @contextconfiguration(classes = { mycontrollertestconfiguration.class }) public class mycontrollertest { @autowired private mycontroller mycontroller; @test public void testdosomething() { mycontroller.dosomething(); } } configuration class:
@configuration public class mycontrollertestconfiguration { @bean public mycontroller mycontroller() { return new mycontroller(); } @bean public myservice myservice() { return mockito.mock(myservice.class); } } and error get: org.springframework.beans.factory.nosuchbeandefinitionexception: no qualifying bean of type [test.test.myrepository] found dependency
i tried initialize mock using mockito's @injectmocks annotation fails because @postconstruct method called before mocks injection, generating nullpointerexception.
and cannot mock repository because in real life make me mock lot of classes...
can me on this?
use interfaces, if use kind of aop (transactions, security, etc), i.e. you'll have interface myservice , class myserviceimpl.
in configuration you'll have:
@bean public myservice myservice() { return mockito.mock(myservice.class); }
Comments
Post a Comment