Nel codice di esempio seguente, se il testMethod() viene eseguito tramite main() funziona come previsto ma se viene eseguito tramite JUNIT, MyUncaughtExceptionHandler non viene richiamato.Java Thread.currentThread(). SetUncaughtExceptionHandler() non funziona con JUNIT?
C'è qualche spiegazione per questo?
package nz.co.test;
import java.lang.Thread.UncaughtExceptionHandler;
import org.junit.Test;
public class ThreadDemo {
private void testMethod() {
Thread.currentThread().setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
Object b = null;
// Cause a NPE
b.hashCode();
}
@Test
public void testJunit() {
// Run via JUnit and MyUncaughtExceptionHandler doesn't catch the Exception
testMethod();
}
public static void main(String[] args) {
// Run via main() works as expected
new ThreadDemo().testMethod();
}
static class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("I caught the exception");
}
}
}
Che cosa è un modo strano per causare NPE, perché non solo 'throw new NullPointerException()'? – kan
lanciare il nuovo NullPointerException() renderebbe il bytecode in testMethod() un po 'diverso. Il codice reale che stavo cercando per testare utilizza l'ottimizzazione bytecode e fa la differenza in quel caso. Se riuscissi a far funzionare tutto come previsto in junit, avrei quindi migliorato testMethod(). –
fornire maggiori dettagli, penso che potremmo trovare un approccio migliore. Forse hai bisogno di generare una nuova discussione, un classloader o anche un'istanza di JVM nel test, ma sarà un test di integrazione, non un test di unità. – kan