'Mockito with Service Class Repo Class and EntityManager

I have classes Two levels to reach the EntityManager

Service Class

class MyServiceClass {
    @Autowired
    MyRepositoryInterfaceImpl repo;

    void myMethod() {
      repo.myMethod();
    }
}

Repo Class

class MyRepositoryInterfaceImpl {
   @Autowire
   EntiryManager em;

   void myMethod() {
      em.getResultList();
   }
}

My question I am able to mock for the class MyRepositoryInterfaceImpl with this code

@ExtendWith(MockitoExtention.class)
class MyRepositoryInterfaceImplTest {
     @InjectMocks
     MyRepositoryInterfaceImpl repo;
     
     @Mock
     EntiryManager em;
}

above code works fine

But I don't want to do that, why can't I directly write test code like this

@ExtendWith(MockitoExtention.class)
class MyServiceClassTest {
     @InjectMocks
     MyServiceClass service;

     @InjectMocks
     MyRepositoryInterfaceImpl repo;
     
     @Mock
     EntiryManager em;
}

and directly mock entity manager from this level ? and call service.myMethod() will it automatically propagate and trigger the entity manager mock ?

but it is not happening that way



Solution 1:[1]

This doesn't work because @InjectMock is not treated as @Mock.

From a UnitTest perspective it is desired to only test one thing/unit.

so you only need to mock the Repository and forget about the EntityManger. Instead use Mockito.when(repo.findAll()).thenReturn(Collections.emptyList()) for UnitTests.

When you want to test the integration between the Service- and RepositoryLayer. You can write an IntegrationTest.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 roy man