简体   繁体   中英

Mockito is not mocking when a service is injected into another service

I have a springboot Rest application where one service has to invoke another service method. The reason being when an employee is created in the system, it has to create default role and group for that employee. The flow is REST call to Employee controller-> createEmp service -> this inturn calls createrole service & creategroup service. The functionality works fine. The problem is with Junits. When i try to mock creategroup and createrole calls in createEmp service, actual methods are being called.

IEmpGroupService empGroupService;
IEmpRoleService empRoleService;
     createEmp  { 
    //logic goes here
    emprepo.save();
    empgroupservice.createDefaultgroup();
    empRoleservice.createDefaultRole();      
    }

Any pointers here please?

Since you're writing unit tests for createEmp service, you should not care about what empgroupservice and empRoleservice do inside them ie you should mock them in you junit tests.

You can inject them at class level (using @Mock ) in you junit class something like this:

....

@Mock
empgroupservice mockedEmpgroupservice;

@Mock
empRoleservice mockedEmpRoleservice;

...

public void testCreateEmp(){
    ...
    Mockito.doNothing().when(mockedEmpgroupservice).createDefaultgroup();
    Mockito.doNothing().when(empRoleservice).createDefaultRole();
    ...
    // invoke your method under test
    ...
    Mockito.verify(mockedEmpgroupservice).createDefaultgroup(customer);
    Mockito.verify(empRoleservice).createDefaultRole();
}

...

Remember to verify their invocations as some of the expectations of your test.

PS. I'd also suggest you to follow naming conventions for your class names. For eg. empGroupService should be EmployeeGroupService .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM