Java: using registrar in JUnit assert *

In JUnit, I want to do the following:

assertTrue(logger.error("the condition is not true"), <a boolean condition>); 

so that the error message is logged by the logger, where the logger could be, for example, commons or log4j.

But the Junit statement does not accept the logger parameter, so is there any way to achieve this, or do I need to try to catch assert and write the error message to the catch block?

+4
source share
3 answers

You can use the JUnit TestRule TestWatcher . A TestRule executes the code before and after the test method (similar to @Before and @After ), but you have access to additional information and, more importantly, the test result. A TestWatcher defines methods such as succeeded() , failed() , starting() and finished() , which you can implement to receive event notifications.

The following example simply prints failed tests with failed statements.

 public class TestWatcherTest { @Rule public TestWatcher testWatcher = new TestWatcher() { protected void failed(Throwable e, Description description) { System.out.println("" + description.getDisplayName() + " failed " + e.getMessage()); super.failed(e, description); } }; @Test public void test1() { Assert.assertEquals("hello world", 3, 4); } } 

You obviously can do what you like, not System.out.println (). This produces as output:

 test1(uk.co.farwell.junit.TestWatcherTest) failed hello world expected:<3> but was:<4> 

Note that a failed statement is an exception, so you will have access to stacktrace, etc.

+19
source

I will not modify or extend the JUnit classes.

The location in which you tried / caught and logged errors would be preferable.

The problem is that giving up Assert is not necessarily an exception.

It looks like you are trying to make log4j available for reporting. I would advise you to look into the Ant JUnit reporting task - this will give you a nice report that will be more useful than a magazine.

UPDATE:

You can always add another log4j extension file. Let log4j write messages to both the console and the file you select. No changes to your code at all, if I'm right.

+3
source

Better use it then

 if(!<condition>) { logger.error("my message"); Assert.fail(); } 
+2
source

Source: https://habr.com/ru/post/1414103/


All Articles