1
    Class MyClass{
    method3(){
      if(condition){
        method1()
      }

      else{

      method2()

      }

    }

     method1(){
     //do woo
      }

     method3(){
        //do foo
      }
 }

I am trying to test method3 only if case is called so else method is not called.

   MyClass myClassMock=   mock(MyClass.class);
         myClassMock.method3();
         verify( myClassMock, times(0)).method2();

But then this calls my method2 and throws null pointer inside method2. How can I test this without calling method2 because my behavior wont call method2.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
javascriptlearner
  • 181
  • 2
  • 3
  • 12
  • Once I fixed the compilation problems this test snippet worked just fine for me. Could you include a [mcve]? – Mureinik Nov 23 '16 at 19:15

1 Answers1

1

If you don't care what was returned from method2 you can mock the method as well:

when(mock.method2(anyString())).thenAnswer("anything");

You can replace anyString and use the following:

when(mock.method2(any(MyClass.class))).thenReturn(anInstanceOfMyClass);

or

verify(mock, never()).method2();

or

when(mock.method2()).thenReturn(instanceOfProperClass);
xenteros
  • 15,586
  • 12
  • 56
  • 91