spring boot Junit单元测试_spring 普通项目单元测试

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(672)   2024-04-17 12:31:27
首先,讲解的是spring 普通项目的Junit单元测试。

举例maven项目。
首先引入spring 项目Junit单元测试需要的必须依赖
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.0.8.RELEASE</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

编写一个测试的基础类
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Log4jConfigurer;

import java.io.FileNotFoundException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-*.xml"})
public class BaseTest {
  
}
其他类只要继承该类就可以不用每次配置spring环境了

常见问题:
log4j:WARN No appenders 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.
解决spring Junit测试log4j环境初始化,在基础测试类中配置log4j的配置文件
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Log4jConfigurer;

import java.io.FileNotFoundException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/springConfig/*.xml"})
public class BaseTest {
    /***
     * 初始化log4j配置
     */
    static {
        try {
            Log4jConfigurer.initLogging("classpath:systemConfig/log4j.properties");
        } catch (FileNotFoundException ex) {
            System.err.println("Cannot Initialize log4j");
        }
    }
}
标签:
地址:https://www.leftso.com/article/423.html

相关阅读

spring boot Junit单元测试_spring 普通项目单元测试
spring boot 2.0 入门之单元测试多线程。spring boot 2.0 项目含多线程异步处理业务单元测试执行主线程结束不等待子线程结束。
maven package打包项目跳过Junit测试
一般spring框架与junit的整合测试都是通过注解@ContextConfiguration,配置其中的localtions加载的xml配置
spring boot又一个spring框架的经典项目,本文讲解spring boot入门的环境配置以及第一个项目,Spring Boot 入门教程
Spring Boot 2.0 Redis整合,通过spring boot 2.0整合Redis作为spring缓存框架的实现。
spring boot项目运行单元测试失败,报错Could not load TestContextBootstrapper [null]. Specify @BootstrapWith's '...
spring boot mybatis 整合使用讲解介绍,spring boot与mybaties的使用讲解介绍。spring boot mybatis xml mapper方式的入门和通过一个...
在Java编程测试中junit5 新特性与使用,Java编程,junit5
Java编程中Spring Boot整合RabbitMQ实现消息中间件RabbitMQ的使用