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) {
}
});
}
1
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) {
}
}
1
Well, for THAT code, you could inject a mocked Text-object and fetch the keyListener after return and call keyReleased on this, e.g. using mockito
@Test
void doTest(){
Text mock = mock(Text.class);
StaticClass.addEnterListener(mock, ....);
ArgumentCaptor<KeyListener> captor = ArgumentCaptor.forClass(KeyListener.class);
verify(mock).addKeyListener(captor.capture());
KeyListener theListener = captor.getValue();
theListener.keyReleased(...);
}
I did not test this, but this should be the way…
though i would encourage to refactor this…
As a third option, refactor creation of the KeyListener into a getKeyListener method. Call that method from your test code to get a KeyListener to test. Also call it in addEnterListener to get the KeyListener to add.
As I suspected, apparently we are not supposed to test anon class methods, according to a colleague ? We refactor code to named methods to accommodate testing.