模拟一个超类构造函数 [英] Mock a superclass constructor

查看:89
本文介绍了模拟一个超类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以模拟超类构造函数调用及其super()调用.

I would like to know if I can mock a super class constructors call and its super() calls.

例如,我有以下课程

class A
{
    A(..)
    {
        super(..)
    }
}   

class B extends A
{
    B(C c)
    {
        super(c)
    }
}

因此,我打算对B类中的某些方法进行单元测试,但是在创建实例时,它确实会调用超类构造函数,因此很难编写单元测试.因此,我该如何模拟所有超类构造函数调用.另外,我想模拟A类中的一些方法,以便它确实根据需要返回一些值.

So, I am planning to unit test some methods in class B, but when creating an instance it does call the super class constructors making it tough to write unit tests. So, how can I mock all the super class constructor calls. Also I would like to mock few methods in class A so that it does return few values as I need.

谢谢!

推荐答案

您可以使用PowerMock库.当您需要完成自己的任务时,它确实是一个救命稻草. https://github.com/powermock/powermock/wiki/Suppress-Unwanted-行为

You could use PowerMock library. It is really a lifesaver when you need to accomplish things like yours. https://github.com/powermock/powermock/wiki/Suppress-Unwanted-Behavior

这篇关于模拟一个超类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆