【发布时间】: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