[英]Always return NullPointerException in array list when mocking in controller
I try to make simple unit test using JUnit and Mockito in the controller.我尝试在 controller 中使用 JUnit 和 Mockito 进行简单的单元测试。 I mocked the service because it will be called by the controller.
我嘲笑了这个服务,因为它会被 controller 调用。 Here is the code
这是代码
@RunWith(MockitoJUnitRunner.class)
class MsCustomerControllerTest {
@Mock
MsCustomerService customerServiceMock;
@InjectMocks
MsCustomerController customerController;
@Test
void test() {
fail("Not yet implemented");
}
@Test
public void findAllCustomerTest() {
List<MsCustomer> listCustomer = new ArrayList<MsCustomer>();
listCustomer.add(new MsCustomer(1, "Rosa", "Titian Indah", LocalDateTime.now()));
listCustomer.add(new MsCustomer(2, "Rosa2", "Titian Indah2", LocalDateTime.now()));
when(customerServiceMock.findAllCustomer()).thenReturn(listCustomer);
ResponseEntity response = new ResponseEntity(listCustomer, HttpStatus.OK);
assertEquals(response, customerController.findAllCustomer());
}
}
note: the customerController also return response entity, so assert with response entity too.注意:customerController 也返回响应实体,因此也使用响应实体进行断言。
Here is the result这是结果
I have tried other method and it also give me the NullPointerException.我尝试了其他方法,它也给了我 NullPointerException。
Try adding an init method and annotate it with @BeforeEach
.尝试添加一个 init 方法并使用
@BeforeEach
对其进行注释。 Then inside the method add MockitoAnnotations.initMocks(this);
然后在方法里面添加
MockitoAnnotations.initMocks(this);
which initializes fields annotated with Mockito annotations.它初始化使用 Mockito 注释注释的字段。
@RunWith(MockitoJUnitRunner.class)
class MsCustomerControllerTest {
@Mock
MsCustomerService customerServiceMock;
@InjectMocks
MsCustomerController customerController;
@BeforeEach
void initMock() {
MockitoAnnotations.initMocks(this);
}
@Test
void test() {
fail("Not yet implemented");
}
@Test
public void findAllCustomerTest() {
List<MsCustomer> listCustomer = new ArrayList<MsCustomer>();
listCustomer.add(new MsCustomer(1, "Rosa", "Titian Indah", LocalDateTime.now()));
listCustomer.add(new MsCustomer(2, "Rosa2", "Titian Indah2", LocalDateTime.now()));
when(customerServiceMock.findAllCustomer()).thenReturn(listCustomer);
ResponseEntity response = new ResponseEntity(listCustomer, HttpStatus.OK);
assertEquals(response, customerController.findAllCustomer());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.