Trimming Stack Traces for Testing

Marcio EndoMarcio EndoApr 30, 2025

Sometimes, during a test, I might create an arbitrary exception to verify if the class I'm working on behaves correctly:

IOException readException = new IOException("Read error");InputStream is = new TestingInputStream(readException);Socket socket = new TestingSocket(is);MyClass component = new MyClass(socket);// test component

In this particular test, though the exception will be logged, I'm not interested in its stack trace. So, I'll trim the throwable's stack trace with the following method:

public static <T extends Throwable> T trimStackTrace(T t, int newLength) {  StackTraceElement[] stackTrace;  stackTrace = t.getStackTrace();  StackTraceElement[] copy;  copy = Arrays.copyOf(stackTrace, newLength);  t.setStackTrace(copy);  return t;}

Which I'll use like so:

IOException readException = trimStackTrace(new IOException("Read error"), 1);

And the stack trace will contain a single element:

java.io.IOException: Read Error
	at objectos.way/objectos.way.HttpExchangeTest0Read.read05(HttpExchangeTest0Read.java:143)