spring 单元测试及其错误整理
目录:
- NO1 spring单元测试方法
- NO1.1 pom.xml文件中确认有下面依赖
- NO1.2 在需要测试的类上,或者新建的测试类上添加注解
- NO1.3 注解说明 - NO2 spirng单元测试错误整理
- NO2.1 java.lang.IllegalStateException: Failed to load ApplicationContext
- NO2.2 java.lang.NoSuchMethodError: org.springframework.util.Assert.notNull
- NO2.3 The import org.springframework.test.context.junit4.SpringJUnit4ClassRunner cannot be resolved
NO1 spring 单元测试方法
NO1.1 pom.xml文件中确认有下面的依赖
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--spring单元测试依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<!--确保版本与其他spring开头的依赖相同 -->
<version>5.0.6.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<!--确保版本与其他spring开头的依赖相同 -->
<version>5.0.6.RELEASE</version>
</dependency>
NO1.2 在需要测试的类上,或者新建的测试类上添加注解
package com.authrization;
import com.authrization.dao.RoleDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/**
* @author weicong
* @data 2018/6/1 12:02
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:config/spring*.xml"})
@WebAppConfiguration
public class TestBBB {
@Autowired
RoleDao roleDao;
@Test
public void testddd(){
System.out.println(roleDao.listRoles());
}
}
NO1.3 注解说明
(1)如果 @ContextConfiguration 有多个xml文件可以这样写
@ContextConfiguration(locations = {"classpath*:config/spring-context*.xml","classpath*:config/spring-mvc.xml"})
(2)有些web项目中不用加 @WebAppConfiguration 也可以运行单元测试
NO2 spirng 单元测试错误整理
NO2.1 java.lang.IllegalStateException: Failed to load ApplicationContext
可能原因:
(1)缺乏 servlet-api 依赖
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
(2)测试类上缺乏 @WebAppConfiguration 注解
NO2.2 java.lang.NoSuchMethodError: org.springframework.util.Assert.notNull
可能原因:
(1)**spirng-test ** 依赖版本与spring全家桶(spring-core、spring-beans、spring-web等等)的依赖版本相差太大,尽量保持spring系列依赖版本全部相同
参看:
https://stackoverflow.com/questions/28013452/could-not-load-testcontextbootstrapper-spring-unit-testing
(2)重复的依赖
NO2.3 java.lang.NoClassDefFoundError: org/springframework/core/ErrorCoded
可能原因:
(1)缺乏 spring-core 依赖
NO2.3 The import org.springframework.test.context.junit4.SpringJUnit4ClassRunner cannot be resolved
原因:maven依赖指定了在test范围才生效
解决:去掉