Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the Loglevel for a JUnit Test

I am using java logging in my classes.

Example:

public class MyClass  {
    private static Logger logger = Logger.getLogger(MyClass.class.getName());
    ....
}

When I am writing a JUnit Test for that class, I would like to set the Loglevel to 'FINE'. I tried:

@Before
public void setup() throws PluginException {
    Logger.getGlobal().setLevel(Level.FINE);
    ....
}

But this has no effect. How can I control the loglevel in a JUnit Test when using Java Logging? I am running my tests using Maven.

like image 587
Ralph Avatar asked Jul 25 '16 11:07

Ralph


People also ask

How do you change Loglevel?

To change log levels as a root user, perform the following: To enable debug logging, run the following command: /subsystem=logging/root-logger=ROOT:change-root-log-level(level=DEBUG) To disable debug logging, run the following command: /subsystem=logging/root-logger=ROOT:change-root-log-level(level=INFO)

How do I enable debug in JUnit?

Debugging a Test Failure Set a breakpoint at the beginning of the test method. Select the test case and execute Debug As>JUnit Test from the Debug drop down.


1 Answers

This is the simplest, most generic way I've found to set the java.util.logging level for JUnit tests.

import java.util.logging.Level;
import java.util.logging.Logger;

import org.junit.BeforeClass;
import org.junit.Test;

public class MyTest
{
    @BeforeClass
    public static void beforeClass()
    {
        System.setProperty("java.util.logging.config.file", ClassLoader.getSystemResource("logging.properties").getPath());
    }

    @Test
    public void test00a()
    {
        Logger.getLogger(MyTest.class.getName()).log(Level.FINE, "J.U.L. test");
    }
}

In src/test/resources create logging.properties (.level must be the first line):

.level=FINEST
handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=FINEST

When you run the unit test(s) in this class, you should see:

May 01, 2017 12:17:12 PM MyTest test00a

FINE: J.U.L. test

like image 56
vallismortis Avatar answered Nov 15 '22 17:11

vallismortis