I am trying to mock an Impl that contains 2 static members A, B, and a static method Utils.SomeMethod. I tried to mix PowerMock and Mockito initially but was not sure if this was causing the problem so I changed all refs to PowerMockito. I get unit test failures that mocks are not getting invoked. if I remove statics and just use Mockito then all tests succeed.
Here is a brief outline of the problem.
class Impl {
static A a;
static B b;
private static final String s = Utils.SomeMethod();
void mainMethod() {
a.aMethod("foo");
b.bMethod("bar");
}
}
So in my unit test I have
@PowerMockIgnore({"javax.net.ssl.*" , "javax.crypto.*"})
@RunWith(PowerMockRunner.class)
@PrepareForTest({Utils.class})
public class ImplTest {
A a;
B b;
@Captor
ArgumentCaptor<String> argumentCaptor;
@BeforeClass
static public void setUp() {
PowerMockito.mockStatic(Utils.class);
PowerMockito.when(Utils.SomeMethod()).thenReturn("test"); // works
}
@Before
public void before() {
a = PowerMockito.mock(A.class);
b = PowerMockito.mock(B.class);
impl = PowerMockito.mock(Impl.class);
impl.setA(a); // I tried @Mock and @InjectMocks but seemed to not work on statics, works with non static members
impl.setB(b);
}
@Test
public void test() {
PowerMockito.when(a
.aMethod(any(String.class))
.thenReturn("hmm");
PowerMockito.when(b.bMethod(any(String.class))
.thenReturn("yo");
impl.mainMethod();
verify(a, times(1)).aMethod(argumentCaptor.capture());
// fails that 0 times mock was invoked
}
}