Java – How to invoke anonymous functions in testing

javaunit testing

Below is Java code.

I need to cover the below function. I searched for many websites, but I still have no ideas. Is there any methods to cover the override anonymous classes?

  public static void addEnterListener(Text text, final String methodName, final Object callee) {
    text.addKeyListener(new KeyListener() {
    @Override
    public void keyReleased(KeyEvent arg0) {
    if (arg0.keyCode == '\r') {
      try {
        Method method = callee.getClass().getMethod(methodName, KeyEvent.class);
        method.invoke(callee, arg0);
      } catch (Exception e) {e.printStackTrace();}
    }
  }

  @Override
  public void keyPressed(KeyEvent arg0) { 
  }
});
}

Best Answer

No, there is no way to do that with annonymous classes.

You can refactorize your code so:

  public static void addEnterListener(Text text, final String methodName, final Object callee) {
    text.addKeyListener(new MyKeyListener());
  }

  class MyKeyListener implements KeyListener {
    @Override
    public void keyReleased(KeyEvent arg0) {
      if (arg0.keyCode == '\r') {
        try {
          Method method = callee.getClass().getMethod(methodName, KeyEvent.class);
          method.invoke(callee, arg0);
        } catch (Exception e) {e.printStackTrace();}
      }
    }

    @Override
    public void keyPressed(KeyEvent arg0) { 
    }
  }
Related Topic