Spring + Spring MVC + mybatis 下的 junit4 注入單元測試

spring環境下的JUnit4測試



1.下載所需jar包:

spring-test-4.0.2.RELEASE.jar

junit-4.11.jar


Maven

<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.0.2.RELEASE</version>
		</dependency>
             <dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
	 </dependency>




以上2個包必須加入spring-test.jar集成了spring測試環境,缺了包不能正常注入。一般測試注入不成功應該是缺這包導致。junit 測試包儘可能應用高點版本,我所應用的是4.11版


@RunWith(SpringJUnit4ClassRunner.class)  

  • 讓測試運行於Spring測試環境Spring框架在org.springframework.test.annotation 包中提供了常用的Spring特定的註解集,如果你在Java5或以上版本開發,可以在測試中使用它


@ContextConfiguration(locations={"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})  

  • locations:可以通過該屬性手工指定 Spring 配置文件所在的位置,可以指定一個或多個 Spring 配置文件。如下所示:
  • @ContextConfiguration(locations={“spring1.xml”,”spring2.xml”}),locations路徑爲在classes文件夾下或Maven resources下,q且配置文件下路徑用classpath:指定,否則特殊情況下識別路徑有誤。
  • inheritLocations:是否要繼承父測試用例類中的 Spring 配置文件,默認爲 true。
  • 若寫classpath*:spring-mvc.xml 和 classpath*:spring-mybatis.xml代表所有資源文件遍歷,首先會查main資源,之後查找test資源


@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations={"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"}) 
public class cTest {

	@Autowired
	public AdminService adminService;
	
	@Test
	public void test() {
		
		Admin a = new Admin();
		a.setUsername("user");
		a.setPassword("sds");
		adminService.insertSelective(a);
	}

}




總結不好多多擔待,文章只單純個人總結,如不好勿噴,技術有限,有錯漏麻煩指正提出。本人QQ:373965070

發佈了49 篇原創文章 · 獲贊 79 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章