zoukankan      html  css  js  c++  java
  • 单元测试类、Log4j、Logback、SLF4j

    SpringBoot 单元测试

    依赖

    		<!--核心 POM,包含自动配置支持、日志库和对 YAML 配置文件的支持-->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    

    创建测试类

    • @RunWith:使用一种运行方式运行测试类(SpringJUnit4ClassRunner让测试运行于Spring测试环境、SpringRunner继承自SpringJUnit4ClassRunner)
    • @SpringBootTest:classes属性解决了测试类路径与源码路径不一致时,找不到@springbootconfig报错的问题
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = ArticleRepositoryTest.class)  
    public class ArticleRepositoryTest {
        @Test
        public void getArticlesByAjax() throws Exception {
            List<Article> articles = articleRepository.getArticlesByUserId();
            articles.get(2);
        }
    }
    

    SSM 单元测试

    依赖

        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>4.1.3.RELEASE</version>
        </dependency>
          
        <!-- 集成junit -->
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
        </dependency>
    

    测试类

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({"classpath:springMVC.xml", "classpath:applicationContext.xml"})
    public class TestDao {
        @Resource
        RoleMapper roleMapper;
    
        @Test
        public void test1(){
            List<Auth> auths = roleMapper.listAuth();
            System.out.println("auths = " + auths);
        }
    }
    

    Logback+SLF4j

    springboot默认日志实现:logback

    依赖

                    <!-- 包含logback、Slf4j-->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter</artifactId>
    		</dependency>
    

    配置

    • 两种方式配置日志规则,这里都使用到了,在yml中配置logback-spring.xml位置

    application.yml

    logging:
      config: classpath:logback-spring.xml
      level:
        # 这里可以是包名也可以是类名
        # DEBUG<INFO<WARN<ERROR<FATAL
        com.hd.dao: info
        org:
          mybatis: info
    

    logback-spring.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <configuration>
    
        <!--0. 日志格式和颜色渲染 -->
        <!-- 彩色日志依赖的渲染类 -->
        <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
        <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
        <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
        <!-- 彩色日志格式 -->
        <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
    
        <!-- 配置控制台输出 -->
        <appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender">
            <!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
            <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
                <level>debug</level>
            </filter>
            <encoder>
                <pattern>${CONSOLE_LOG_PATTERN}</pattern>
                <!-- 设置字符集 -->
                <charset>UTF-8</charset>
            </encoder>
        </appender>
    
        <!-- 配置文件输出(Info)-->
        <appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <encoder>
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            </encoder>
            <!-- 滚动策略-->
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 文件位置 -->
                <fileNamePattern>e:/log/info-%d.log</fileNamePattern>
            </rollingPolicy>
        </appender>
    
        <!-- 配置文件输出(Error)-->
        <appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <!--添加 范围 过滤-->
            <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
                <level>ERROR</level>
            </filter>
            <encoder>
                <pattern>%d -- %msg%n</pattern>
            </encoder>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>e:/log/error-%d.log</fileNamePattern>
            </rollingPolicy>
        </appender>
    
        <root level="info">
            <appender-ref ref="consoleLog" />
            <appender-ref ref="fileInfoLog" />
            <appender-ref ref="fileErrorLog" />
        </root>
    </configuration>
    

    使用日志输出

    public class LoggerTest {
        private final Logger logger = LoggerFactory.getLogger(LoggerTest.class);
    
        @Test
        public void test(){
            logger.debug("debug...");
            logger.info("info...");
    
        }
    }
    

    Log4j+SLF4j

    依赖

        <!-- Log4j 日志实现-->
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.16</version>
        </dependency>
        <!-- Slf4j 日志门面-->
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.12</version>
        </dependency>
        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.7.12</version>
        </dependency>
    

    配置
    log4j.properties

    # Global logging configuration
    log4j.rootLogger=ERROR, stdout
    # MyBatis logging configuration...
    log4j.logger.com.hd=TRACE
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{[yyyy-MM-dd HH:mm:ss]} %m %n
    

    日志输出

    public class LogTest {
        static final Logger logger = LoggerFactory.getLogger(LogTest.class);
    
        @Test
        public void test(){
            logger.error("error...");
        }
    }
    

    避坑

    logback日志控制台无效
    测试日志本地生成有效说明springbooot已经加载了logback-spring.xml,clean maven后rebuild后解决

  • 相关阅读:
    解决方案-BI:百科
    un-Error-ASP.NET:“/tbm6”应用程序中的服务器错误。
    JS-jQuery-EasyUI-Layout-Tabs:Tabs 标签页/选项卡
    JS-jQuery-EasyUI-Layout:Layout 布局
    jQuery-EasyUI-CSS:Icon 图标
    jQuery-EasyUI:Layout
    JS-jQuery-EasyUI:CSS
    JS-jQuery-EasyUI :目录
    ORM:百科
    ORM- IBatisNet:百科
  • 原文地址:https://www.cnblogs.com/xiongyungang/p/13997486.html
Copyright © 2011-2022 走看看