My go-with solution will also be an IDE filter, as others have already pointed out. If you execute a โhard-codedโ solution, this will be less visible during the automatic build process.
In Eclipse, you can open the settings and select Java -> JUnit and add classes or packages using the buttons on the right.
But just for fun:
If you really want to do this programmatically, @gar's solution sounds pretty reasonable. However, if you have more statements, it can be a little tedious.
What you can also do is subclass AssertionError and the stacktrace filter in its root.
public class MyAssertionError extends AssertionError { public MyAssertionError(String message) { super(message); } @Override public synchronized Throwable fillInStackTrace() { super.fillInStackTrace(); filterStackTrace(); return this; } protected void filterStackTrace() { StackTraceElement[] trace = getStackTrace(); ArrayList<StackTraceElement> list = new ArrayList<StackTraceElement>(trace.length); for (StackTraceElement element : trace) { if (!element.getClassName().equals("newassertions.MyAssertions")) { list.add(element); } } this.setStackTrace(list.toArray(new StackTraceElement[0])); } }
Note two things here: 1) the class name StackTraceElement never be null, so its fine to write a constant on the right side 2) if you put all your statements in a separate package, you can also write element.getClassName().startsWith("newassertions")
Then your approval class will look like this:
package newassertions; public class MyAssertions { public static void myAssertTrue(boolean b) { if (!b) { fail(null); } } public static void fail(String message) { if (message == null) { throw new MyAssertionError(message); } throw new MyAssertionError(message); } }
That way you could not call methods from Assert , but if you write more complex statements, there are several reasons to do so anyway. However, this will keep your confirmation code a bit cleaner than wrapping everything in large try-catch blocks.
Franz becker
source share