Reputation: 43
I try to make simple unit test using JUnit and Mockito in the controller. I mocked the service because it will be called by the 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.
Here is the result
I have tried other method and it also give me the NullPointerException.
Upvotes: 2
Views: 855
Reputation: 1471
Try adding an init method and annotate it with @BeforeEach
.
Then inside the method add MockitoAnnotations.initMocks(this);
which initializes fields annotated with Mockito annotations.
@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());
}
}
Upvotes: 1