Mockito 方法调用存根不起作用 - Mockito.doReturn(false).when(studentServiceImpl).myClass().isValidUser(ArgumentMatchers.anyInt());

Mockito method call stub not working - Mockito.doReturn(false).when(studentServiceImpl).myClass().isValidUser(ArgumentMatchers.anyInt());

为 getStudent 方法添加测试用例,这是内部调用

1- 是存储库调用 - 存根这个调用工作正常

2- 验证用户调用 - 存根这个调用不起作用,显示一些错误和测试用例失败。

服务Class

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    FakeStudentRepository fakeStudentRepository;
    @Override
    public Optional<Student> getStudent(int id) {
        Optional<Student> student = fakeStudentRepository.getStudent(id);
        boolean isValid = myClass().isValidUser(student.get().getId());
        if(!isValid) {
            return Optional.empty();
        }
        return student;
    }
    public MyTestClass myClass() {
        return new MyTestClass();
    }
 }

MyTestClass

public class MyTestClass {
    public boolean isValidUser(int id) {
        return true;
    }
}

测试Class

@SpringBootTest
class StudentServiceImplTest {

    @Mock
    FakeStudentRepository fakeStudentRepository;

    @InjectMocks
    StudentServiceImpl studentServiceImpl;

    @BeforeEach
    public void setup() {
        studentServiceImpl = Mockito.spy(StudentServiceImpl.class);
        MockitoAnnotations.initMocks(this);
    }

    @Test
    void getStudent() {
        Optional<Student> student = Optional.of(Student.builder().id(1).firstName("Rahul").lastName("rahul")
                .mobile("XXXXXX").build());

        Mockito.doReturn(student)
                .when(fakeStudentRepository).getStudent(ArgumentMatchers.anyInt());

        Mockito.doReturn(false)
                .when(studentServiceImpl).myClass().isValidUser(ArgumentMatchers.anyInt());

        Optional<Student> resultStudent = studentServiceImpl.getStudent(student.get().getId());
        assertEquals(resultStudent.get().getId(), student.get().getId());
    }
}

错误

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: Boolean cannot be returned by myClass() myClass() should return MyTestClass

If you're unsure why you're getting above error read on. Due to the nature of the syntax above problem might occur because: 1. This exception might occur in wrongly written multi-threaded tests. Please refer to Mockito FAQ on limitations of concurrency testing. 2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

错误消息表明:您正在模拟 studentServiceImpl.myClass() 并尝试 return 为真。当您尝试使用第二个 Mockito 表达式时,不可能模拟调用链的结尾。

要执行您想要的操作,首先需要通过 return 模拟 class 实例并在其上模拟 isValidUser 来模拟 myClass()