Mock local variable in Junit, Mockito


I’m working on a test case for a code using Mockito. The code looks like this,

public class Example {
 private HelperService hs; 

 public void someMethod() {
   List<String> names = new ArrayList<>();
   if(names.size() < 5) {throw new RuntimeException("Invalid names list");}


public class HelperService {

 public void addValues(List<String> names) {


I know this is a contrived example but I have a similar usecase where I cannot modify the existing code. I want to unit test the Example class using Junit, Mockito. How can I test the exception scenario where names.size() is < 5.


I’m going to assume you already have a means for setting the HelperService field in your test (whether that’s by making it a @SpringBootTest, using @InjectMocks, or something else). So this will just give options for providing one that will let you do what you want:

  1. Extend HelperService and inject that:
// Inject this into your class under test
private HelperService hs = new LessThan5NameAddingHelperService();

class LessThan5NameAddingHelperService extends HelperService {
    public void addNames( List<String> names ) {
        names.add( "Dave" );
  1. Provide a mock HelperService which does the same:
// Inject this into your class under test
private HelperService hs;

public void setupMockHelperService() {
    hs = mock( HelperService.class );

    doAnswer( invocation -> {
        List<String> names = ( List<String> ) invocation.getArguments()[0];
        names.add( "Dave" );
        return null;
    } ).when( hs ).addNames( any() );

Answered By – BeUndead

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published