[英]Mockito mock NullPointerException, don't know what else is there to try
Java thinks my mocked Course class object is null at the line when().thenReturn(). 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;
}
}
I have tried:我努力了:
@RunWith(MockitoJUnitRunner.class)
class StudentTest{...
-- --
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
}
-- --
@Rule public Mocks mocks = new Mocks(this);
none of which solve NPE.没有一个可以解决 NPE。
Also tried (using mocked Teacher object as one of the parameters)也试过(使用mocked Teacher object作为参数之一)
@Mock
Course courseMock1 = new Course(params..);
which yielded: MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'产生: MissingMethodInvocationException: when() 需要一个参数,该参数必须是“模拟方法调用”
Annotate StudentTest
class with @RunWith(MockitoJUnitRunner.class)
.使用
@RunWith(MockitoJUnitRunner.class)
注释StudentTest
class 。
Declare StudentTest
class as public
.将
StudentTest
class 声明为public
。
Declare student_getTeacherNames_should_return_list_of_full_names
method as public
.将
student_getTeacherNames_should_return_list_of_full_names
方法声明为public
。
Run the test class.运行测试 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);
}
}
What test framework are you using?你用的是什么测试框架? junit 4 or junit 5?
junit 4 还是 junit 5?
If junit5, then the test class should be annotated with @ExtendWith(MockitoExtension.class)
如果是junit5,那么测试class应该用
@ExtendWith(MockitoExtension.class)
注解
An alternative could be to rely purely on code (not using annotation).另一种方法可能是纯粹依赖代码(不使用注释)。 The code would become
代码将变为
class StudentTest {
Course courseMock1 = Mockito.mock(Course.class);
...
}
To use @Mock annotations you need to import org.mockito.MockitoAnnotations;要使用 @Mock 注释,您需要导入 org.mockito.MockitoAnnotations; and call MockitoAnnotations.initMocks.
并调用 MockitoAnnotations.initMocks。 Note that the method has to be called before each test.
请注意,必须在每次测试之前调用该方法。
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
}
I used mistakenly @Before instead of @Before Each我错误地使用了@Before 而不是@Before Each
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.