【问题标题】:Mockito method call stub not working - Mockito.doReturn(false).when(studentServiceImpl).myClass().isValidUser(ArgumentMatchers.anyInt());Mockito 方法调用存根不起作用 - Mockito.doReturn(false).when(studentServiceImpl).myClass().isValidUser(ArgumentMatchers.anyInt());
【发布时间】:2020-09-18 17:41:02
【问题描述】:

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

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

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

服务类

@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;
    }
}

测试类

@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: 布尔值 myClass() 不能返回 myClass() 应该返回 MyTestClass

如果您不确定为什么会出现上述错误,请继续阅读。因为 可能会出现上述问题的语法性质,因为: 1. 此异常可能发生在错误编写的多线程测试中。请参阅 Mockito 常见问题解答以了解并发限制 测试。 2. 使用 when(spy.foo()).then() 语法对 spy 进行存根。存根间谍更安全- - 使用 doReturn|Throw() 系列方法。更多关于 Mockito.spy() 方法的 javadocs。

【问题讨论】:

    标签: unit-testing junit mocking mockito junit5


    【解决方案1】:

    错误消息说:你在嘲笑studentServiceImpl.myClass() 并尝试返回true。当您尝试使用第二个 Mockito 表达式时,不可能模拟调用链的结尾。

    要做你想做的事,首先要模拟myClass(),方法是返回一个模拟的类实例,然后模拟isValidUser

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多