Omaja7
Omaja7

Reputation: 129

Mocking field in @Mock class

Since I am new to Mockito, I would like to know, how can I mock a method inside a class, which actually is also annotated with @Mock.

Example:

@RunWith(MockitoJUnitRunner.class)
public class someServiceTest {

@InjectMocks
private MainService mainService;

@Mock
private HelpService helpService;

@Mock
private SecondHelpService secondHelpService;

Now there is this helpService class, which contains a method, which is used to test MainService.

@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class HelpService {

//  I want this method to be mocked
private boolean checkSomething(String name, date) {
    return ProcessService.checkIfJobHasRun(name, date);
}

I tried to use @InjectMocks on HelpService as well, by adding ProcessService @Mock in someServiceTest, but Mockito doesn't allow that. And as a result, it throws me NullPointerException. How do I fix that?

Upvotes: 1

Views: 222

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26572

@InjectMocks should only be used on the class under test. It does not make sense to inject dependencies into mocks as they do not have any implementation.

If you can make the method public you could mock it as follows:

doReturn(true).when(helpService)
              .checkSomething(Mockito.any(String.class), Mockito.any(Date.class));

Upvotes: 1

Related Questions