[PowerMock]Mock构造方法失败解决之道

当使用PowerMock来mock一个对象的构造方法:

    /**
     * do test for constructor
     */
    @Test
    public void testConstructor() throws Exception {
        Hello hello = mock(Hello.class); // mock one object

        // when new one object without any args, will use the mock one instead
        whenNew(Hello.class) //
                .withNoArguments().thenReturn(hello);

        Hello myHello = new Hello(); // the object is mocked one now.

        // because didn't mock the method with value of arg, so will be null
        assertThat(myHello.sayHello("World"), nullValue());
    }

如果测试运行时,报如下错误:

org.mockito.exceptions.misusing.UnfinishedVerificationException: 
Missing method call for verify(mock) here:
...

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.

那是因为mock 类需要提供一个构造方法,默认的构造方法是不支持,所以报错,需要显式的指定默认构造方法:

public class Hello {

    public Hello() {

    }

    ...
}


你可能感兴趣的:(JUnit,Java,mock,powermock)