Spring --单元测试及使用logback打印测试结果

(1)将logback集成到junit中

package com.liutao.utils;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import org.junit.runners.model.InitializationError;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * 将logback集成到junit中
 *
 * @author LIUTAO
 * @version 2017/5/11
 * @see
 * @since
 */
public class JUnit4ClassRunner extends SpringJUnit4ClassRunner {
    static{
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        try {
            configurator.doConfigure("src/main/resources/conf/logback.xml");
        } catch (JoranException e) {
            e.printStackTrace();
        }
    }
    public JUnit4ClassRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }
}
(2)添加单元测试

package com.liutao.test;

import com.liutao.dao.UserDao;
import com.liutao.entity.User;
import com.liutao.mapper.UserMapper;
import com.liutao.utils.JUnit4ClassRunner;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;

/**
 * 测试类
 *
 * @author LIUTAO
 * @version 2017/4/20
 * @see
 * @since
 */
@RunWith(JUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:conf/applicationContext.xml"})
public class TestUser extends TestCase {
    private Logger logger = LoggerFactory.getLogger(TestUser.class);
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserDao userDao;

    @Test
    public void findUser() throws Exception {
        logger.debug("the user is "+userMapper.getUsersByName("zhangfei"));
        logger.debug("the user is "+userMapper.getUsersByName("zhangfei"));
//        userMapper.updateUser(new User("张三丰",11,"zsf123",1));
    }

    @Test
    public void testFindUserByIdOfJpa(){
        logger.debug("this user was found by jpa is "+userDao.findUserById(1));
        logger.debug("this user was found by jpa is "+userDao.findUserById(1));
    }
}

项目代码参考gitHub地址: 单元测试

### 配置 logback-spring.xml 实现日志打印Spring Boot 项目中,`logback-spring.xml` 是用于自定义日志配置的核心文件。以下是关于如何正确配置 `logback-spring.xml` 来实现日志打印的具体方法。 #### 日志配置概述 Spring Boot 启动时会优先加载名为 `logback-spring.xml` 的文件作为日志系统的配置文件[^2]。如果没有找到此文件,则会退而求其次寻找 `logback.xml` 文件。由于 `logback-spring.xml` 支持更多高级功能(如 `${}` 占位符解析和基于 profile 的条件化配置),因此推荐使用它来进行日志管理。 #### 使用占位符引入外部属性 可以通过 `${}` 占位符机制,在 `logback-spring.xml` 中引用来自 `application.yml` 或者 `application.properties` 定义的变量。例如: ```xml <!-- application.yml --> logging: path: /var/log/myapp/ <!-- logback-spring.xml --> <configuration> <!-- 将 logging.path 属性映射到 log.path --> <property name="LOG_PATH" value="${logging.path}" /> <!-- 设置日志文件名 --> <property name="LOG_FILE_NAME" value="my-application.log" /> <!-- 控制台输出 --> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- 文件输出 --> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_PATH}/${LOG_FILE_NAME}</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_PATH}/%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <encoder> <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern> </encoder> </appender> <!-- Root logger level --> <root level="info"> <appender-ref ref="CONSOLE" /> <appender-ref ref="FILE" /> </root> </configuration> ``` 上述代码片段展示了如何设置控制台和文件两种类型的 appender,并利用滚动策略按日期归档日志文件[^4]。 #### 特殊场景下的优化建议 为了适应更复杂的应用需求,可以进一步扩展配置逻辑: - **多环境适配**:借助 `<springProfile>` 标签实现针对开发、测试或生产环境的不同日志级别与路径设定。 ```xml <springProfile name="dev"> <root level="debug"> <appender-ref ref="CONSOLE"/> </root> </springProfile> <springProfile name="prod"> <root level="warn"> <appender-ref ref="FILE"/> </root> </springProfile> ``` - **权限校验**:确保指定的日志目录存在且应用程序对该目录拥有写入权限。 #### 总结 通过合理设计 `logback-spring.xml` 文件结构以及灵活运用其内置特性,能够显著提升项目的可维护性和运行效率。务必注意实际部署环境中可能存在的差异性因素,比如操作系统类型或者磁盘空间限制等问题的影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值