user9333933
user9333933

Reputation: 267

MissingMethodInvocationException when using PowerMockito to test static method

I read several posts about using powermockito instead of just mockito to test static methods, however after switching to power mockito, I'm still getting the same error. Below is my class and the exception. Neither case in the exception explains the error I have.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassToBeMocked.class})
public class Test extends AbstractTestNGSpringContextTests {
    @Mock
    Object1 o1;

    @BeforeMethod
    public void init() {
        mockStatic(ClassToBeMocked.class);

        PowerMockito.when(ClassToBeMocked.getMethod()).thenReturn("string");
    }

The last line of code causes this exception org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because: 1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. Mocking methods declared on non-public parent classes is not supported. 2. inside when() you don't call method on mock but on some other object.

Upvotes: 0

Views: 2063

Answers (2)

Dubius
Dubius

Reputation: 438

I'm actually struggling with a similar problem, but I do see something wrong with the above. The @RunWith annotation are part of the JUnit library. AbstractTestNGSpringContextTests and @BeforeMethod are parts of the TestNG library. That may be why you running into issues. Unless someone wants to contradict this statement, I believe the two unit test libraries do not work with each other. At least not like that.

@RunWith(PowerMockRunner.class) will not be able to pick up @BeforeMethod as though it were org.junit.Before.

Upvotes: 0

emcas88
emcas88

Reputation: 901

Could you try this:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassToBeMocked.class})
public class Test extends PowerMockTestCase {
    @Mock
    Object1 o1;

    @ObjectFactory
    public IObjectFactory getObjectFactory() {
        return new org.powermock.modules.testng.PowerMockObjectFactory();
    }

    @BeforeMethod
    public void init() {
        mockStatic(ClassToBeMocked.class);

        PowerMockito.when(ClassToBeMocked.getMethod()).thenReturn("string");
    }

Upvotes: 0

Related Questions