Junit整合log4j

今天遇到一个Spring Junit整合Log4j的小例子,控制台报了一个警告如下:

log4j:WARN No ppenders could be found for logger(org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

这里的意思就是使用Junit的没时候没有加载log4j.properties配置文件。(因为Junit的运行不通过tomcat是一个独立的路径,所以我们手动的加载log4j配置文件)

我用的是maven创建的工程,所以我就在test测试目录下写了一个Junit4ClassRunner类,并继承了SpringJunit4ClassRunner这个类,使用静态代码块优先加载log4j配置文件。

import org.apache.log4j.PropertyConfigurator;
        import org.junit.runners.model.InitializationError;
        import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
        import java.io.InputStream;

public class Junit4ClassRunner extends SpringJUnit4ClassRunner {
    static {
        InputStream log4j = Junit4ClassRunner.class.getResourceAsStream("/log4j.properties");
        PropertyConfigurator.configure(log4j);
    }

    public Junit4ClassRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }
}

在测试代码中使用自己编写的Junit4ClassRunner类即可。

@RunWith(Junit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class Test_Spring {
    @Resource(name = "accountService")
    private AccountService service;
    @Test
    public void test_AccountService(){
        Account account = new Account();
        account.setId(12);
        service.saveAccount(account);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值