1

I am currently writing unit tests using Junit. I want to access a public static variable and update its value from test class.

Example code:

@RunWith(MockitoJUnitRunner.class)
class A {
    public static final List<String> myList = new ArrayList<String>();
    public int myMethod(){
      if(myList.contains("someString")){
          //make some random calls here
          call_to_some_method();
      } else {
          //make some other calls here
          call_to_another_method();
          // put the value into list for another iteration
          myList.add("addingSomeOtherString");
      }
    }
 public void call_to_some_method() {...}
 public void call_to_another_method() {...}
}

class Test_A {
   public A a;

   @Before
   public void setUp(){
    a = new A;
   }

   @Test
   public void test_List_Values_And_Calls() {
     A.myList.add("someString"); //adding values to myList
     a.myMethod();
     //verifying whether call_to_some_method() is made 
     //since myList.contains("someString") should be true
     Mockito.verify(a, Mockito.times(1)).call_to_some_method(); // The test is failing here
   }
}

The test is failing. Error: "Wanted but Never Invoked". Please let me know why its failing? Is there any better way to access the public static field and update changes in the field from test class? Thanks In Advance!

Siddharth Shankar
  • 489
  • 1
  • 10
  • 21
  • `a` has to be a mock, but isn't. Is that on purpose or why do you use mocking methods without a mock object? – Progman Jun 22 '20 at 18:14
  • Hi @Progman, No reason for not using a mock. Even if I use mock object, I am facing the same issue. – Siddharth Shankar Jun 22 '20 at 18:27
  • 1
    When you use a mock object the whole object is being mocked. You have to use something like `doCallRealMethod()` for the `myMethod()` method or make this specific method `final`. Or use `spy()` as mentioned in the answer. – Progman Jun 22 '20 at 19:09

0 Answers0