Search code examples
javaunit-testingreflectionmockito

How can I mock a local final variable


There a local variable in my method which is final. How can I mock?

public void method(){
  final int i=myService.getNumber();
}

I want to mock

when(myService.getNumber()).thenReturn(1);

How can I complete it with mocking?

My project is using Java 7, is there way using reflection or something else to realize this mock


Solution

  • This request, as stated, doesn't make much sense. Mocking systems don't mock variables (or fields). You could, however, easily set a field to an object you have mocked. Your test would look like this:

    @Test public void methodWithNumberOne {
      MyService myService = Mockito.mock(MyService.class);
      when(myService.getNumber()).thenReturn(1);
    
      // You might want to set MyService with a constructor argument, instead.
      SystemUnderTest systemUnderTest = new SystemUnderTest();
      systemUnderTest.myService = myService;
    
      systemUnderTest.method();
    }
    

    Another way to set it up that doesn't require mocks:

    public void method() {
      method(myService.getNumber());
    }
    
    /** Use this for testing, to set i to an arbitrary number. */
    void method(final int i) {
      // ...
    }