如何在 JMockit Expectations 中模拟具有通用返回类型的函数

问题描述

我希望被模拟的方法返回一个特定的类而不是超类,但是抛出了一个 ClassCastException。不确定如何正确定义期望。任何帮助将不胜感激。

@Component
public class PeopleService {

    public <T extends People> T changeName(T person) {
        person.setName("DifferentName");
        return person;
    }
}

@Component
@requiredArgsConstructor
public class StudentService {

    private final PeopleService peopleService;

    public Student retrieveStudent() {
        Student student = new Student();
        student.setName("name");
        student.setId("id");
        return peopleService.changeName(student);
    }
}

public class StudentServiceTest {

    @Injectable
    private PeopleService peopleService;

    @Tested
    private StudentService target;

    @Test
    public void test_retrieveStudent_Pass() {
        Student student = new Student();

        new Expectations(){{
            peopleService.changeName(student);
            result = student;
        }};

        Student output = target.retrieveStudent();
    }
}
java.lang.classCastException: People cannot be cast to Student
    at StudentService.retrieveStudent(StudentService.java:16)
    at StudentServiceTest.test_retrieveStudent_Pass(StudentServiceTest.java:23)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)