微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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 举报,一经查实,本站将立刻删除。