0

I have class named A that contains private method name a(). Another class, named B() contains public method name b() that called by a().

I'm trying to mock b() and to change his return value by using PowerMocito().

public class A() {

private void a(){
   // logic
   b();
   // logic
}

}

public class B() {

public int b() {
  return 0;
}


My Test method looks like:

@Test 
public void TestB() { 
 // logic
 B mock = PowerMockito.mock(B.class);
        PowerMockito.when(mock.b()).thenReturn(1);
}

The code compiles, but I'm hoping to get 1 but the method returns 0.

  • What exactly are you trying to test? Best post the whole test case, `b() ` isn't even called in your snippet. – daniu Mar 30 '20 at 17:58
  • Two general rules: (1) Only test public API. (Private methods are an implementation detail.) (2) If you need to mock `B.b()` to test `A`, you should be providing an instance of `B` to `A`, probably in `A`'s constructor. – chrylis -cautiouslyoptimistic- Mar 30 '20 at 18:45
  • Does this answer your question? [What is the difference between public, protected, package-private and private in Java?](https://stackoverflow.com/questions/215497/what-is-the-difference-between-public-protected-package-private-and-private-in) – Nikolay Vetrov Mar 30 '20 at 19:07
  • No, I know the differences. Basically, I'm trying to Mock method declared on non-public parent classes - is that even possible? – Ben Moalem Mar 31 '20 at 06:59
  • You might want to edit your code to make sure its syntactical correct. From your last comment I would say that `B extends A`, but that does not match to your declaration in your test. Shouldn't you try to mock `a()` in that case, as that is the non-public method? – second Apr 02 '20 at 13:33

0 Answers0