1

I have a situation like this

class A{


    public method1(){

     result = method2();
    }

    private method2(){
      result = method3()
      some processing;
      return result2;
    }
    private method3(){
      processing;
      return result;

    }
  }

I want to test method1(), but when method2 calls method3, I don't want actual method3 to execute, but return value I want. Is there a way to do this?

coder hacker
  • 4,819
  • 1
  • 25
  • 50
  • 1
    Wouldn't executing method3 be necessary in order to return the result? – deezy Jul 14 '15 at 21:48
  • @DizzyCode For unit tests I want to provide my own results from method3, instead of one returned from executing it. So something like when(method3()).then(my result) – coder hacker Jul 14 '15 at 21:51
  • See http://stackoverflow.com/questions/8799439/testing-private-method-using-mockito – arun Jul 14 '15 at 22:17
  • If you really want your method3 not to be executed, there is a design issue in your class. The method3 should be in another class B, and there would be a dependency of class B in class A which you could stub in your test. Then you would have something like this : when(b.method3()).thenReturn(xxx) – Damien Beaufils Jul 17 '15 at 09:34
  • @DamienBeaufils I realized that, and I put it into a different class. Thanks – coder hacker Jul 17 '15 at 16:25

1 Answers1

-1

The simplest solution is to comment out the line: result = method3() in your implementation of method 2, and instead set result to be equal to the return value that you want from method3.

Rick Ridley
  • 573
  • 2
  • 9