Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test for Save method of JPA Repository in Spring Boot

Can you please tell me how I should write unit tests for this code using Mockito & JUnit? StudentRepository is an interface which extends JPA Repository.

public class StudentService {
    @Autowired
    StudentRepository studentRepository;
    
    public void saveStudentDetails(StudentModel student) {
        Student stud = new Student();
        stud.setStudentId(student.getStudentId());
        stud.setStudentName(student.getStudentName());
        studentRepository.save(stud);
    }
}
like image 991
Ajinkya Jagtap Avatar asked Mar 03 '23 03:03

Ajinkya Jagtap


1 Answers

I've been in this same situation couple days ago, and i figured something like this.

@InjectMocks
StudentService studentService;
@Mock
StudentRepository studentRepository;

public void saveStudentDetailsTest(){
    //given
    StudentModel student = new StudentModel(Your parameters);
    //when
    studentService.saveStudentDetails(student);
    //then
    verify(studentRepository, times(1)).save(any());
}

Also you can use ArgumentCaptor and check if the object you are passing to save is what you want, and it can looks like this

ArgumentCaptor<Student> captor = ArgumentCaptor.forClass(Student.class);
verify(studentRepository).save(captor.capture());
assertTrue(captor.getValue().getStudentName().equals(student.getStudentName()));
like image 83
Boorsuk Avatar answered Mar 05 '23 04:03

Boorsuk