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);
}
}
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With