How to go about mocking a class with final methods?

天大地大妈咪最大 提交于 2019-12-03 14:33:06
Jacek Szymański

You can try the JMockit mocking library.

I'd remove the "final" and just put in a comment "Don't override this method!!". If you can't trust coworkers not to follow simple instructions, it's hopeless anyway.

The following code will also allow you to do it. I am not saying that this is good practice, but it is an interesting use (abuse?) of anonymous classes.

public class Jobber {

    public final String foo() {
        return fooFactory() ;
    }

    String fooFactory() {
        return "jobber" ;
    }


    public static void main(String[] args) {

        Jobber jobber = new Jobber() { String fooFactory() { return "prefix " + super.fooFactory() ;} } ;

        System.out.println(jobber.foo() );
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!