I would like to do some "own stuff" when an assertion in JUnit fails. I would like to have this:
public class MyAssert extends org.junit.Assert {
// @Override
static public void fail(String message) {
System.err.println("I am intercepting here!");
org.junit.Assert.fail(message);
}
}
Of course, this does not work, because you cannot override static methods. But if it would, this would be nice, because every assert function like assertTrue()
calls the fail()
method. Thus, I could easily intercept every assertion.
Does there exist any way to do what I want to do here, without implementing all different flavors of assert...
?
assertTrue()By passing condition as a boolean parameter used to assert in JUnit with the assertTrue method. It throws an AssertionError (without message) if the condition given in the method isn't True.
assertNotEquals. Asserts that two objects are not equals. If they are, an AssertionError without a message is thrown. If unexpected and actual are null , they are considered equal.
assertEquals() is the method of Assert class in JUnit, assertThat() belongs to Matchers class of Hamcrest. Both methods assert the same thing; however, hamcrest matcher is more human-readable. As you see, it is like an English sentence “Assert that actual is equal to the expected value”.
You should take a look at the Rules, that were introduced in Junit 4.7. Especially TestWatchman:
TestWatchman is a base class for Rules that take note of the testing action, without modifying it. For example, this class will keep a log of each passing and failing test:
http://junit-team.github.io/junit/javadoc/4.10/org/junit/rules/TestWatchman.html
It lets you define a MethodRule that can handle failing Tests (Copy from the javadoc):
@Rule
public MethodRule watchman= new TestWatchman() {
@Override
public void failed(Throwable e, FrameworkMethod method) {
watchedLog+= method.getName() + " " + e.getClass().getSimpleName()
+ "\n";
}
@Override
public void succeeded(FrameworkMethod method) {
watchedLog+= method.getName() + " " + "success!\n";
}
};
@Test
public void fails() {
fail();
}
@Test
public void succeeds() {
}
As per comment TestWatchman is depecreated in newer Versions of Junit and replaced with TestWatcher (but the functionality is the same):
http://junit-team.github.io/junit/javadoc/4.10/org/junit/rules/TestWatcher.html
You could write a class that implements exactly the same signatures of all the methods in Assert and then delegates to the Assert methods.
public class MyAssert {
static public void assertTrue(String message, boolean condition) {
Assert.assertTrue(message, condition);
}
...
static public void fail(String message) {
System.err.println("I am intercepting here!");
Assert.fail(message);
}
}
Not exactly re-implementing all the methods, but tedious nonetheless. Your IDE may be able to help in generating the delegate methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With