目錄:java
<!-- 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>
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()); } }
(1)若是 @ContextConfiguration 有多個xml文件能夠這樣寫web
@ContextConfiguration(locations = {"classpath*:config/spring-context*.xml","classpath*:config/spring-mvc.xml"})
(2)有些web項目中不用加 @WebAppConfiguration 也能夠運行單元測試spring
可能緣由:
(1)缺少 servlet-api 依賴bootstrap
<!-- 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 註解api
可能緣由:
(1)spirng-test 依賴版本與spring全家桶(spring-core、spring-beans、spring-web等等)的依賴版本相差太大,儘可能保持spring系列依賴版本所有相同
參看:
https://stackoverflow.com/questions/28013452/could-not-load-testcontextbootstrapper-spring-unit-testing
spring-mvc
(2)重複的依賴mvc
可能緣由:
(1)缺少 spring-core 依賴app
緣由:maven依賴指定了在test範圍才生效
解決:去掉