在Spring中整合JUnit單元測試-創(chuàng)新互聯(lián)

一 簡介

在Java Web開發(fā)中,通常我們會開發(fā)很多的功能代碼。在代碼正式使用之前,為了確保代碼能夠正確實現(xiàn)我們預(yù)期的功能,最好是添加一些簡單代碼對代碼邏輯進行測試。很顯然,JUnit就是一個不錯的單元測試工具,同時在Spring中我們也可以很方便地引入JUnit進行測試

成都創(chuàng)新互聯(lián)公司主要從事做網(wǎng)站、網(wǎng)站制作、網(wǎng)頁設(shè)計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)邢臺,十多年網(wǎng)站建設(shè)經(jīng)驗,價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):13518219792

二 代碼實例

(1)引入必需的jar包:

這里除了Spring以及其他模塊所需要的jar包之外,還需要引入:

  • spring-test-4.2.3.RELEASE.jar

  • junit-4.10.jar

注:jar包版本使用最新穩(wěn)定版即可

(2)測試項目目錄結(jié)構(gòu)以及配置:

在Spring中整合JUnit單元測試

上面圖中的一些目錄是我自己新建的,為的就是將不同功能的文件分隔開。這個Demo項目采用的技術(shù)是:Spring + Spring MVC + Mybatis + MySQL + Druid連接池

context.xml文件是一些基本配置;springmvc-servlet.xml文件是 Spring MVC相關(guān)的配置;sql-map-config.xml文件是Mybatis相關(guān)配置。下面我粘貼下web.xml文件和context.xml文件的代碼供大家參考,其他的一些配置文件跟這里關(guān)系不大就不粘貼出來了

i)web.xml:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
	  http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath:context/context.xml
		</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:context/springmvc-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<!-- <url-pattern>*.html</url-pattern> -->
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>

	<filter>
		<filter-name>characterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<servlet>
		<servlet-name>DruidStatView</servlet-name>
		<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>DruidStatView</servlet-name>
		<url-pattern>/druid/*</url-pattern>
	</servlet-mapping>
	<filter>
		<filter-name>druidWebStatFilter</filter-name>
		<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
		<init-param>
			<param-name>exclusions</param-name>
			<param-value>/public/*,*.js,*.css,/druid*,*.jsp,*.swf</param-value>
		</init-param>
		<init-param>
			<param-name>principalSessionName</param-name>
			<param-value>sessionInfo</param-value>
		</init-param>
		<init-param>
			<param-name>profileEnable</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>druidWebStatFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

ii)context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:cache="http://www.springframework.org/schema/cache" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/cache  
       		http://www.springframework.org/schema/cache/spring-cache-4.0.xsd  
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop">

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>

	<!-- Druid連接池,文檔:https://github.com/alibaba/druid/wiki/常見問題 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		destroy-method="close">
		<!-- 數(shù)據(jù)庫基本信息配置 -->
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<property name="driverClassName" value="${driverClassName}" />
		<property name="filters" value="${filters}" />
		<!-- 大并發(fā)連接數(shù) -->
		<property name="maxActive" value="${maxActive}" />
		<!-- 初始化連接數(shù)量 -->
		<property name="initialSize" value="${initialSize}" />
		<!-- 配置獲取連接等待超時的時間 -->
		<property name="maxWait" value="${maxWait}" />
		<!-- 最小空閑連接數(shù) -->
		<property name="minIdle" value="${minIdle}" />
		<!-- 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
		<!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
		<property name="validationQuery" value="${validationQuery}" />
		<property name="testWhileIdle" value="${testWhileIdle}" />
		<property name="testOnBorrow" value="${testOnBorrow}" />
		<property name="testOnReturn" value="${testOnReturn}" />
		<property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
		<!-- 打開 removeAbandoned 功能 -->
		<property name="removeAbandoned" value="${removeAbandoned}" />
		<!-- 1800 秒,也就是 30 分鐘 -->
		<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
		<!-- 關(guān)閉 abanded 連接時輸出錯誤日志 -->
		<property name="logAbandoned" value="${logAbandoned}" />
	</bean>

	<!-- MyBatis相關(guān)配置 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:context/sql-map-config.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="cn.zifangsky.mapper" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>

	<!-- 事務(wù)相關(guān)配置 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

注:jdbc.properties文件:

url: jdbc:mysql://localhost:3306/cookie_db
driverClassName: com.mysql.jdbc.Driver
username: root
password: root
filters: stat,wall
maxActive: 100
initialSize: 10
maxWait: 60000
minIdle: 10
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 123
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
maxOpenPreparedStatements: 20
removeAbandoned: true
removeAbandonedTimeout: 1800
logAbandoned: true

(3)新建測試的DAO層的代碼:

由于我這里使用的是Mybatis,因此就直接使用“mybatis-generator”插件自動生成一些基本文件了

注:關(guān)于“mybatis-generator”插件的使用想了解更多可以參考我的這篇文章:https://www.zifangsky.cn/431.html

(4)單元測試示例:

在src/test/java目錄下新建TestUserTable.java,其內(nèi)容如下:

package cn.zifangsky.test.base;

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.SpringJUnit4Cla***unner;

import cn.zifangsky.mapper.UserMapper;
import cn.zifangsky.model.User;
import junit.framework.Assert;

@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration(locations={"classpath:/context/context.xml"})
public class TestUserTable {
	@Autowired
	UserMapper userMapper;
	
	@Test
	public void testSelectByPrimaryKey(){
		User user = userMapper.selectByPrimaryKey(1);
		
//		System.out.println(user.getName());
		Assert.assertEquals("admin", user.getName());  //預(yù)期值-實際值
	}

}

關(guān)于這里的代碼我簡單解釋下:

  1. @RunWith注解配置了此次測試使用的環(huán)境

  2. @ContextConfiguration注解配置了基本的Spring配置文件的路徑

  3. UserMapper 是一個具體的DAO層的類,使用@Autowired注解自動注入到這個單元測試中

  4. @Test注解標注的方法被當做一個測試方法,里面的內(nèi)容隨意。當然,這里僅僅只是測試了根據(jù)主鍵查詢一個實體

  5. junit.framework.Assert 這個類可以用于斷言,這里就是判斷從數(shù)據(jù)庫中查出來的用戶名是否為“admin” 。如果是,那么此次測試成功,如果不是則測試失敗。如果不習慣這種寫法的話還可以使用我注釋掉的那樣直接在控制臺中打印一些數(shù)據(jù),然后我們再手動判斷

(5)運行單元測試:

關(guān)于單元測試,可以有以下幾種方式來運行測試,分別是:

  1. 在標注了@Test注解的方法上鼠標右鍵選擇:Run As –> JUnit Test ,這種方式測試的就是這一個方法

  2. 在一個單元測試的Java類上鼠標右鍵選擇JUnit單元測試,這種方式測試的是這個類中的所有標有@Test注解的方法

  3. 在一個包或者一個目錄上選擇JUnit單元測試。很顯然,這種方式的測試的實例更多

如果一個方法測試成功,那么在JUnit視圖中是這樣的:

在Spring中整合JUnit單元測試

相反,測試失敗顯示的視圖是這樣的:

在Spring中整合JUnit單元測試

PS:上面圖片中的水印是我個人博客的域名,因此還請管理員手下留情不要給我標為“轉(zhuǎn)載文章”,謝謝!?。?/p>

創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動態(tài)BGP最優(yōu)骨干路由自動選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機房獨有T級流量清洗系統(tǒng)配攻擊溯源,準確進行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動現(xiàn)已開啟,新人活動云服務(wù)器買多久送多久。

網(wǎng)站標題:在Spring中整合JUnit單元測試-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://muchs.cn/article2/coccic.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、搜索引擎優(yōu)化虛擬主機、定制開發(fā)、建站公司、網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運營