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范圍才生效
解決:去掉