Home > Back-end >  Mock local variable in Junit, Mockito
Mock local variable in Junit, Mockito

Time:09-28

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

public class Example {
 
 @Autowired
 private HelperService hs; 

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

}

public class HelperService {

 public void addValues(List<String> names) {
  names.add("alex");
  names.add("harry");
  names.add("james");
  names.add("maria");
  names.add("bob");
 }

}

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.

CodePudding user response:

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 {
    @Override
    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;

@Before
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() );
}
  • Related