[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() {

    }

    ...
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值