覆盖通过反射或其它手段的java最终方法呢?

问题描述 投票:10回答:6

在试图写测试用例出现这个问题。 foo是框架库,我没有到源代码访问中的一类。

public class Foo{
  public final Object getX(){
  ...
  }
}

我的应用程序会

public class Bar extends Foo{
  public int process(){
    Object value = getX();
    ...
  }
}

单元测试情况下是无法初始化为我不能由于其他依赖创建Foo对象。所述BarTest抛出一个空指针作为值为空。

public class BarTest extends TestCase{
  public testProcess(){
    Bar bar = new Bar();        
    int result = bar.process();
    ...
  }
}

有没有一种方法,我可以使用反射API到的getX()设置为非决赛?或者我应该如何去测试?

java reflection methods final
6个回答
5
投票

你可以创建你可以在您的测试覆盖另一种方法:

public class Bar extends Foo {
  protected Object doGetX() {
    return getX();
  }
  public int process(){
    Object value = doGetX();
    ...
  }
}

然后,你可以在BarTest覆盖doGetX。


19
投票

由于这是在谷歌“重写最后方法的java”顶部结果中的一个。我以为我会离开我的解决方案。这个类展示了使用如“贝果”类和免费使用了Javassist库的简单解决方案:

/**
 * This class shows how you can override a final method of a super class using the Javassist's bytecode toolkit
 * The library can be found here: http://jboss-javassist.github.io/javassist/
 * 
 * The basic idea is that you get the super class and reset the modifiers so the modifiers of the method don't include final.
 * Then you add in a new method to the sub class which overrides the now non final method of the super class.
 * 
 * The only "catch" is you have to do the class manipulation before any calls to the class happen in your code. So put the
 * manipulation as early in your code as you can otherwise you will get exceptions.
 */

package packagename;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.Modifier;

/** 
 * A simple class to show how to use the library
 */
public class TestCt {

    /** 
     * The starting point for the application
     */
    public static void main(String[] args) {

        // in order for us to override the final method we must manipulate the class using the Javassist library.
        // we need to do this FIRST because once we initialize the class it will no longer be editable.
        try
        {
            // get the super class
            CtClass bagel = ClassPool.getDefault().get("packagename.TestCt$Bagel");

            // get the method you want to override
            CtMethod originalMethod = bagel.getDeclaredMethod("getDescription");

            // set the modifier. This will remove the 'final' modifier from the method.
            // If for whatever reason you needed more than one modifier just add them together
            originalMethod.setModifiers(Modifier.PUBLIC);

            // save the changes to the super class
            bagel.toClass();

            // get the subclass
            CtClass bagelsolver = ClassPool.getDefault().get("packagename.TestCt$BagelWithOptions");

            // create the method that will override the super class's method and include the options in the output
            CtMethod overrideMethod = CtNewMethod.make("public String getDescription() { return super.getDescription() + \" with \" + getOptions(); }", bagelsolver);

            // add the new method to the sub class
            bagelsolver.addMethod(overrideMethod);

            // save the changes to the sub class
            bagelsolver.toClass();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        // now that we have edited the classes with the new methods, we can create an instance and see if it worked

        // create a new instance of BagelWithOptions
        BagelWithOptions myBagel = new BagelWithOptions();

        // give it some options
        myBagel.setOptions("cheese, bacon and eggs");

        // print the description of the bagel to the console.
        // This should now use our new code when calling getDescription() which will include the options in the output.
        System.out.println("My bagel is: " + myBagel.getDescription());

        // The output should be:
        // **My bagel is: a plain bagel with cheese, bacon and eggs**
    }

    /**
     * A plain bagel class which has a final method which we want to override
     */
    public static class Bagel {

        /**
         * return a description for this bagel
         */
        public final String getDescription() {
            return "a plain bagel";
        }
    }

    /**
     * A sub class of bagel which adds some extra options for the bagel.
     */
    public static class BagelWithOptions extends Bagel {

        /**
         * A string that will contain any extra options for the bagel
         */
        String  options;

        /**
         * Initiate the bagel with no extra options
         */
        public BagelWithOptions() {
            options = "nothing else";
        }

        /**
         * Set the options for the bagel
         * @param options - a string with the new options for this bagel
         */
        public void setOptions(String options) {
            this.options = options;
        }

        /**
         * return the current options for this bagel
         */
        public String getOptions() {
            return options;
        }
    }
}

2
投票

勒布是正确的,只是确保你得到一个回答你的问题,在原生代码做一些事情的(我敢肯定那就没办法了),或者修改类的字节码在运行时,并创建类覆盖方法在运行时,我看不到的方式来改变的方法“finalness”。反射不会帮助你在这里。


0
投票

如果你的单元测试的情况下不能创建美孚由于其他的依赖关系,这可能是你没有将你的单元测试的权利摆在首位的标志。

单元测试是指在相同条件下生产的代码将运行测试,所以我建议你重新创建测试内部相同的生产环境。否则,你的测试将是不完整的。


0
投票

如果getX()返回的变量不final您可以使用该技术在What’s the best way of unit testing private methods?解释了通过private改变Reflection变量的值。


0
投票
public class Bar extends Foo{
  public int process(){
    Object value = getX();
    return process2(value);
  }
  public int process2(Object value){
  ...
  }
}

public class BarTest extends TestCase{
  public testProcess(){
    Bar bar = new Bar();   
    Mockobj mo = new Mockobj();     
    int result = bar.process2(mo);
    ...
  }
}

我做了什么,而最终在上面。这是一个有点难看......詹姆斯的解决方案肯定比这更好?

© www.soinside.com 2019 - 2024. All rights reserved.