如何为JUnit测试设置Loglevel [英] How to set the Loglevel for a JUnit Test

查看:811
本文介绍了如何为JUnit测试设置Loglevel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的课程中使用java日志。

I am using java logging in my classes.

示例:

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

当我写JUnit测试时那个班,我想把Loglevel设置为'FINE'。我试过了:

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);
    ....
}

但这没有效果。
如何在使用Java Logging时控制JUnit Test中的loglevel?
我正在使用Maven运行我的测试。

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.

推荐答案

这是我发现设置 java.util的最简单,最通用的方法。记录 JUnit测试的级别。

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");
    }
}

src / test /资源创建 logging.properties .level 必须是第一行):

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:


2017年5月1日12:17:12 PM MyTest test00a

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

FINE:JUL测试

FINE: J.U.L. test

这篇关于如何为JUnit测试设置Loglevel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆