Search code examples
javaspringspring-mvcjunitmockito

Spring Framework - Mock is not mocking


I have a Spring MvC app. (The Spring Framework is an application framework and inversion of control container for the Java platform) with this test:

    @RunWith(SpringJUnit4ClassRunner.class)
    public class AutorisationServiceTest {
    
        @Autowired
        @InjectMocks
        private IAutorisationService service;
    
        @Mock
        PersonneRepository personneRepository = Mockito.mock(PersonneRepository.class);
    
    
        @Before
        public void setup() {
        }
    
    
        @Test
        public void should_Find_GardeWith2Affectations() throws IOException {
    
            when(personneRepository.getAll(anyString())).thenReturn(DataLoader.mockData());
            service.getAll("rules");
        }
    
    }

    @Service
    public class AutorisationService implements IAutorisationService {
    
        private final PersonneRepository personneRepository;
    
        public AutorisationService(PersonneRepository personneRepository) {
            this.personneRepository = personneRepository;
        }

@Override
    public List<User> getAll(String where) {
        return personneRepository.getAll(where));
    }
    ...
    }

but when I run the test it seems no to mock the repo


Solution

  • You should decide whether you want to write a Spring test or a Mockito test.

    A spring test will load the full context and you can then work with @Autowired and @MockBean:

    @RunWith(SpringJUnit4ClassRunner.class)
    public class AutorisationServiceTest {
        
      @Autowired
      private IAutorisationService service;
        
      @MockBean
      PersonneRepository personneRepository;
    

    A Mockito test runs much faster, but you will only have the objects you explicitly configured with @InjectMocks or @Mock:

    @RunWith(MockitoJUnitRunner.class)
    public class AutorisationServiceTest {
      
      @InjectMocks
      private IAutorisationService service;
        
      @Mock
      PersonneRepository personneRepository;
    

    Note that you never have to instanciate the mock with Mockito.mock() when using annotations and specialized runners.

    I guess your PersonneRepository is a @Service, @Component or @Repository. So you should use auto-wiring here as well:

    @Service
    public class AutorisationService implements IAutorisationService {
    
       @Autowired    
       private PersonneRepository personneRepository;