Search code examples
javaspringjunitmockitoeclipselink

test returning NULL when saving


I have this class:

@Repository
public interface EnfantRepository extends JpaRepository<Enfant, Long> {

..
}

and this service:

@Transactional
@Service
@Slf4j
public class EnfantService implements IEnfantService {

    public Enfant save (Enfant enfant) {
        return enfantRepository.save(enfant);
    }
}

and this test:

@RunWith(MockitoJUnitRunner.class)
public class EnfantServiceTest {

    @Mock
    private EnfantRepository enfantRepository = mock(EnfantRepository.class);

    @InjectMocks
    private EnfantService enfantService;

    @Test
    public void testSave() {

        System.out.println(enfantService.save(Enfant.builder().build()));

        Assertions.assertThat
                (enfantService.save(Enfant.builder().build())).isNotNull();

    }
}

but it return null after save and the test fails


Solution

  • Over here in the EnfantServiceTest class, you have mocked the EnfantRepository class and there is no implementation provided for the method inside that mocked EnfantRepository class. So, calling any method will return null.

    There are two ways here:

    1. Stub for the save method for your mocked class EnfantRepository using "when" & "then" of Mockito.
    @RunWith(MockitoJUnitRunner.class)
    public class EnfantServiceTest {
    
       @Mock
       private EnfantRepository enfantRepository = mock(EnfantRepository.class);
    
       @InjectMocks
       private EnfantService enfantService;
    
       @Test
       public void testSave() {
    
           System.out.println(enfantService.save(Enfant.builder().build()));
           
           when(enfantRepository.save(any()).thenReturn(Long.of(1));
    
           Assertions.assertThat
                   (enfantService.save(Enfant.builder().build())).isNotNull();
    
       }
    }
    But this wont be a good way of testing the repository code. Rather,
    
    1. Use an in-memory database like H2 for your test environment and in that case no need to mock the Repository class. While running tests, Spring will bring up H2 database and then it will connect to that database and create tables from your entities class and performs all the queries against that database. This will ensure your code is working as expected end to end.