【发布时间】:2020-04-29 07:38:09
【问题描述】:
Java 认为我模拟的 Course 类对象在 when().thenReturn() 行为 null。
class StudentTest {
@Mock
Course courseMock1;
@Test
void student_getTeacherNames_should_return_list_of_full_names() {
when(courseMock1.getEAP()).thenReturn(1);
}
public class Course {
public Course(String courseName, String name, LocalDate startDate, LocalDate endDate, Integer EAP, Teacher teacher) {
this.courseName = courseName;
this.name = name;
this.startDate = startDate;
this.endDate = endDate;
this.EAP = EAP;
this.teacher = teacher;
}
public Integer getEAP() {
return EAP;
}
}
我试过了:
@RunWith(MockitoJUnitRunner.class)
class StudentTest{...
--
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
}
--
@Rule public Mocks mocks = new Mocks(this);
没有一个能解决 NPE。
也尝试过(使用模拟的 Teacher 对象作为参数之一)
@Mock
Course courseMock1 = new Course(params..);
产生了: MissingMethodInvocationException: when() 需要一个参数,该参数必须是“模拟方法调用”
【问题讨论】:
-
最简单的版本是
Course courseMock = Mockito.mock(Course.class),但请注意不要模拟数据类;只需创建一个eap为 1 的实例。 -
这行得通!那么注释有问题吗?另外,初学者问题,eap 为 1 的实例类型是什么?模拟数据类有什么不好?
-
注解没有什么错误,只是支持注解的基础设施比
mock(Course.class)更复杂,一般来说最好让事情尽可能简单。不应模拟数据类,因为它们不做任何事情,它们只是具有值,因此new Course("courseName", "name", LocalDate.now(), LocalDate.now(), 1, null)为您提供所需的 EAP==1,而不会产生不必要的复杂性。
标签: java nullpointerexception mocking mockito