Issue
I'm working on the JUnit tests for these methods, I've spend a couple of hours trying to improve it with no success, the test is passing but I'm getting 0% coverage, any idea why am I getting that?
AuthService.java
public String getUsers() {
if (studentBean.getUsers() == null || checkIfTokenExpired()) {
this.fetchStudents();
}
return studentBean.getUsers();
}
public boolean checkIfTokenExpired() {
LocalDateTime currentDateTime = LocalDateTime.now();
LocalDateTime expiryTime = setExpiryTime();
boolean isTokenExpired = currentDateTime.isAfter(expiryTime);
return isTokenExpired;
}
JUnit test:
@Mock
StudentBean studentBean;
@Mock
AuthService authService;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetUsers(){
Mockito.when(studentBean.getUsers()).thenReturn(null);
Mockito.when(authService.checkIfTokenExpired()).thenReturn(false);
Mockito.when(authService.getUsers()).thenReturn("APSAPS");
assertEquals("APSAPS", authService.getUsers());
}
Thank you!
Solution
You should inject the mocks in your AuthService.
You can do that using @InjectMocks
Also, since you want to test "getUsers" method you should not mock the method for it.
We only mock the methods of the mocked attributes not the service under test.
@Mock
StudentBean studentBean;
@InjectMocks
AuthService authService;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetUsers(){
Mockito.when(studentBean.getUsers()).thenReturn(null);
//Mockito.when(authService.checkIfTokenExpired()).thenReturn(false);
//Mockito.when(authService.getUsers()).thenReturn("APSAPS");
// assertEquals("APSAPS", authService.getUsers());
String result = authService.getUsers();
//... perform assertions
}
with this code your fetchStudents method will be triggered and you should Assert the same.
Answered By - Ankit Sharma
Answer Checked By - Marie Seifert (JavaFixing Admin)