Issue
I have this test: but the method checkIfHold is also mocked
@RunWith(MockitoJUnitRunner.class)
public class FrontSecurityServiceTest {
@Mock
private FrontSecurityService frontSecurityService
= mock( FrontSecurityService.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
@Test
public void test1() {
when(frontSecurityService.getLoggedInUserId()).thenReturn("000");
frontSecurityService.checkIfHold(9L);
}
}
I also tried with
@Mock
PerService perService;
@Spy
private FrontSecurityService frontSecurityService = new FrontOfficeSecurityService(perService);
but then is not mocking the method getLoggedInUserId()
, getLoggedInUserId is public, non-static, and non-final.
I also tried, there it works, but MenService is called inside checkIfHold is null
@RunWith(SpringJUnit4ClassRunner.class)
public class FrontSecurityServiceTest {
@Mock
MenService menService;
@Mock
FrontSecurityService frontSecurityService;
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Test
public void test1() {
MenReturn menReturn1 = MenReturn.builder().build();
when(menService.getMen(anyString(), anyLong())).thenReturn(Arrays.asList(menReturn1));
when(frontSecurityService.checkIfHold(anyLong())).thenCallRealMethod();
when(frontSecurityService.getLoggedInUserId()).thenReturn("000");
frontSecurityService.checkIfHold(9L);
}
}
Solution
I guess that @Spy
is what you are looking for. Still, testing FrontSecurityService
and also mock it at the same time seems odd to me.
Try the following:
@RunWith(MockitoJUnitRunner.class)
public class FrontSecurityServiceTest {
@Spy
private FrontSecurityService frontSecurityService;
@Test
public void test1() {
when(frontSecurityService.getLoggedInUserId()).thenReturn("000");
frontSecurityService.checkIfHold(9L);
}
}
Answered By - João Dias
Answer Checked By - Terry (JavaFixing Volunteer)