18

I would like to display a warning in a JUnit test. I don't want the test to fail because of that warning but I would like to know that the warning occurs. Obviously, I can use System.err.print or something similar. Now I wonder what is the right way to do it

4

3 回答 3

9

I have also thought that this would useful at times, but this can't be done. JUnit insists on a right and wrong answer and so only has "success", "fail", and "error". Error being when something breaks in the code while running the test. I would refactor and consider if you really need a warning (or log like the previous answer suggests, although I think this warning would soon get lost),

于 2012-12-25T08:53:02.993 回答
6

use logger with console appender for it

final Logger logger = LoggerFactory.getLogger(LoggingTest.class);

@Test
public void test() {
    logger.warn("message");
}  

PS. Example using slf4j logger.

于 2012-12-25T08:46:33.223 回答
2

you can have log4j configuration specific to your tests.

Step 1: create a file src/test/resources/test-log4j.properties containing the configuration of log4j for your tests.

Example:

log4j.rootLogger=DEBUG, R
log4j.appender.R=org.apache.log4j.ConsoleAppender
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{3}:%L - %m%n

Step 2: Edit your pom.xml like the following:

<build>
 ...
 <plugins>

   <plugin>
     <artifactid>maven-surefire-plugin</artifactid>
     <version>2.3</version>
     <configuration>
       <systemproperties>
         <property>
           <!-- Specific log4j config for tests -->
           <name>log4j.configuration</name>
           <value>test-log4j.properties</value>
         </property>
       </systemproperties>
     </configuration>
   </plugin>
   ...
 </plugins>
</build>

Now your log4j.properties is located in src/main/webapp/WEB-INF/classes/

Hope this helps.

于 2012-12-25T08:57:38.430 回答