在控制器中模拟时,数组列表中总是 return NullPointerException

Always return NullPointerException in array list when mocking in controller

我尝试在控制器中使用 JUnit 和 Mockito 进行简单的单元测试。我嘲笑该服务,因为它会被控制器调用。 这是代码

@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());
    }

}

注意:customerController 也 return 响应实体,因此也使用响应实体进行断言。

这是结果

我试过其他方法,它也给我 NullPointerException。

尝试添加一个 init 方法并用 @BeforeEach 注释它。 然后在方法中添加 MockitoAnnotations.initMocks(this); 初始化用 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());
    }

}