javarandomjunitmockitointegration-testing

How can I access the internal variable of a method in Java junit?


I have a function in which a random number is generated as shown below

public void method(){
     int number = random();
     // continue
}

My question is how can I access this variable without mocking random method?

I need this variable for my test scenarios.


Solution

  • One thing you can do if you really need this is refactor your code:

    @RequiredArgsConstructor
    public class MyClass {
     private<Supplier<Integer>> final random;
     
     public void method() {
      int number = random.get();
      // ...
     }
    }
    

    You can then inject it in the test

    public class MyTest {
     @Test
     public void testMethod() {
      Supplier<Integer> supplier = () -> 3;
      MyClass sut = new MyClass(supplier);
      sut.method(); // random in method will be 3
     }
    }
    

    However, I assume you're doing something like this

    public void method() {
     int random = random.get(),
     service.call(random);
    }
    

    then you can use an ArgumentCaptor.

    @Test
    public void testMethod() {
     Service service = mock(Service.class);
     MyClass sut = new MyClass(service);
     sut.method();
     ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class);
     verify(service).call(captor.capture());
     // captor.value() now contains the value you're looking for
    }