[英]I have a NullPointerException in a mock, and I don't know what to do
[英]Mockito mock NullPointerException, don't know what else is there to try
Java 认为我的模拟课程 class object 是 Z37A6259CC0C1DAE299A7866489DFF0(在该行时)。
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。
也试过(使用mocked Teacher object作为参数之一)
@Mock
Course courseMock1 = new Course(params..);
产生: MissingMethodInvocationException: when() 需要一个参数,该参数必须是“模拟方法调用”
使用@RunWith(MockitoJUnitRunner.class)
注释StudentTest
class 。
将StudentTest
class 声明为public
。
将student_getTeacherNames_should_return_list_of_full_names
方法声明为public
。
运行测试 class。
@RunWith(MockitoJUnitRunner.class)
public class StudentTest {
@Mock
Course courseMock1;
@Test
public void student_getTeacherNames_should_return_list_of_full_names() {
Mockito.when(courseMock1.getEAP()).thenReturn(1);
assertThat(courseMock1.getEAP()).isEqualTo(1);
}
}
你用的是什么测试框架? junit 4 还是 junit 5?
如果是junit5,那么测试class应该用@ExtendWith(MockitoExtension.class)
注解
另一种方法可能是纯粹依赖代码(不使用注释)。 代码将变为
class StudentTest {
Course courseMock1 = Mockito.mock(Course.class);
...
}
要使用 @Mock 注释,您需要导入 org.mockito.MockitoAnnotations; 并调用 MockitoAnnotations.initMocks。 请注意,必须在每次测试之前调用该方法。
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
}
我错误地使用了@Before 而不是@Before Each
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.