Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

java - Retuning Empty List After Call ServiceClass Method from Testing Class

Retuning Empty List after call getStudentDetails() I have written one Studentservice class and one StudentRepo Interface and want to junit test of service class using junit5 with mockito.

Expecting Size of List is 2 but return 0. please follow below code for reference

Student Service Class

@Service
public class StudentService {

    @Autowired
    StudentRepo studentRepo;
    
    public List<Student> getStudentDetails(){
        
        List<Student> students = studentRepo.findAll();
        
        for(Student student : students) {
            student.setMarks(50);
        }
        return students;
    }
}

StudentService testing class

@WebMvcTest(StudentService.class)
public class StudentServiceTest {

    @MockBean
    StudentRepo studentRepoMock;
    
    @Mock
    StudentService studentServiceMock;
    
    
    @Test
    public void test() {
        
        
        when(studentRepoMock.findAll()).thenReturn(
                Arrays.asList(new Student(1,"abc"),
                (new Student(2,"def"))
                ));
        
        
        List<Student> student=studentServiceMock.getStudentDetails();  //return empty List
        
        
        verify(studentServiceMock, Mockito.times(1)).getStudentDetails(); /*it's working*/

        System.out.println(student.size());  
        
        //assertEquals(50,student.get(0).getMarks());
        //assertEquals(50,student.get(1).getMarks());
        
    }   
}
    

any help would be appreciated


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have mocked both the repository and the service. You are never calling any real functionality that way. If you want to test StudentService, you have to let Spring at least instantiate it by replacing @Mock with @Autowired on the StudentService.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...