微信公眾號【黃小斜】大廠程序員,互聯網行業新知,終身學習踐行者。關注后回復「Java」、「Python」、「C++」、「大數據」、「機器學習」、「算法」、「AI」、「Android」、「前端」、「iOS」、「考研」、「BAT」、「校招」、「筆試」、「面試」、「面經」、「計算機基礎」、「LeetCode」 等關鍵字可以獲取對應的免費學習資料。
package com.junit;public class method_junti {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public int division(int a, int b) {
return a / b;
}}
package com.junit;import static org.junit.Assert.*;import org.junit.Test;public class junit_test {
//測試方法必須有@test;
//該測試方法必須由public void修飾,沒有返回值;
//該方法不帶任何參數;
//新建一個源代碼測試文件單獨存放測試代碼;
//測試類的包和被測試類的包保持一致;
//測試方法間互相獨立沒有任何依賴;
@Test public void testAdd(){
assertEquals(4, new method_junti().add(3, 0));
}
@Test public void testSubtract(){
assertEquals(3, new method_junti().subtract(6, 3));
}
@Test public void testMultiply(){
assertEquals(6, new method_junti().multiply(6, 1));
}
@Test public void testDivision(){
assertEquals(6, new method_junti().division(6, 1));
}}
package com.junit;import static org.junit.Assert.*;import org.junit.Test;public class method_juntiTest2 {
@Test public void testAdd() {
fail("Not yet implemented");
}
@Test public void testSubtract() {
fail("Not yet implemented");
}
@Test public void testMultiply() {
fail("Not yet implemented");
}
@Test public void testDivision() {
fail("Not yet implemented");
}}
@Testpublic void testAdd(){
assertEquals(3, new method_junti().add(3, 0));}
@Testpublic void testDivision(){
assertEquals(6, new method_junti().division(6, 1));}
package com.junit;import org.junit.After;import org.junit.AfterClass;import static org.junit.Assert.*;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;public class Junit_case {
@BeforeClass public static void setUpBeforeClass() throws Exception {
}
@AfterClass public static void tearDownAfterClass() throws Exception {
}
@Before public void setUp() throws Exception {
}
@After public void tearDown() throws Exception {
}
@Test public void test() {
fail("Not yet implemented");
}}
package com.junit;import static org.junit.Assert.*;import org.junit.After;import org.junit.AfterClass;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;public class Junit_test1 {
/* 1、BeforeClass修飾的方法會在所有方法被調用前執行
* 而且該方法是靜態的,所以當測試類被加載后接著就執行它
* 在內存中它只會存在一份,適合加載配置文件
* 2、AfterClass修飾的方法用來對資源的清理,如關閉數據庫的連接
* befoer和after修飾的方法在每個test修飾的方法執行前會被各執行一次,假如有兩個
* test文件,before和after會被各執行兩次;
* */
@BeforeClass public static void setUpBeforeClass() throws Exception {
System.out.println("this is beforeclass");
}
@AfterClass public static void tearDownAfterClass() throws Exception {
System.out.println("this is afterclass");
}
@Before public void setUp() throws Exception {
System.out.println("this is before");
}
@After public void tearDown() throws Exception {
System.out.println("this is after");
}
@Test public void test1() {
System.out.println("this is test1");
}}
@Test(expected=ArithmeticException.class)public void testDivision(){
assertEquals(6, new method_junti().division(6, 0));}
@Test(timeout=2000)//單位是毫秒
public void testWhile(){
while(true){
System.out.println("run forever");
}}
import static org.junit.Assert.*;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.Suite;import org.junit.runners.Suite.SuiteClasses;@RunWith(Suite.class)@Suite.SuiteClasses({TaskTest1.class,TaskTest2.class,TaskTest3.class})public class SuitTest {
public void test(){
/*
* 由于在開發的項目中,測試的類很多,一個一個運行很浪費時間,于是可以寫一個測試
* 套件把所有需要測試的類組合在一起測試運行
* 1、寫一個測試入口,這個類不含其它的方法;
* 2、更改測試運行器@RunWith(Suite.class)
* 3、將要測試的類作為數組放在@Suite.SuiteClasses({})中;
*/
}}
package com.junit;import static org.junit.Assert.*;import java.util.Arrays;import java.util.Collection;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.Parameterized;import org.junit.runners.Parameterized.Parameters;@RunWith(Parameterized.class)public class ParameterTest {
//聲明變量存放預期值和測試數據;
int expected=0;
int input1=0;
int input2=0;
@Parameters public static Collection<Object[]> test(){
return Arrays.asList(new Object[][]{
{3,1,2},
{4,2,2}
});
}
public ParameterTest(int expected,int input1,int input2){
this.expected=expected;
this.input1=input1;
this.input2=input2;
}
@Test public void testAdd(){
assertEquals(expected, new method_junti().add(input1, input2));
} }
遇到問題多思考、多查閱、多驗證,方能有所得,再勤快點樂于分享,才能寫出好文章。
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<!-- 初始化數據表結構 -->
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:h3/schema.sql" encoding="UTF-8"/>
<jdbc:script location="classpath:h3/data-prepare-*.sql" encoding="UTF-8"/>
</jdbc:initialize-database>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${user.jdbc.url}"/>
<property name="username" value="${user.jdbc.username}"/>
<property name="password" value="${user.jdbc.password}"/>
<!-- 連接池初始連接數 -->
<property name="initialSize" value="3"/>
<!-- 允許的最大同時使用中(在被業務線程持有,還沒有歸還給druid) 的連接數 -->
<property name="maxActive" value="30"/>
<!-- 允許的最小空閑連接數,空閑連接超時踢除過程會最少保留的連接數 -->
<property name="minIdle" value="3"/>
<!-- 從連接池獲取連接的最大等待時間 5 秒-->
<property name="maxWait" value="5000"/>
<!-- 強行關閉從連接池獲取而長時間未歸還給druid的連接(認為異常連接)-->
<property name="removeAbandoned" value="true"/>
<!-- 異常連接判斷條件,超過180 秒 則認為是異常的,需要強行關閉 -->
<property name="removeAbandonedTimeout" value="180"/>
<!-- 從連接池獲取到連接后,如果超過被空閑剔除周期,是否做一次連接有效性檢查 -->
<property name="testWhileIdle" value="true"/>
<!-- 從連接池獲取連接后,是否馬上執行一次檢查 -->
<property name="testOnBorrow" value="false"/>
<!-- 歸還連接到連接池時是否馬上做一次檢查 -->
<property name="testOnReturn" value="false"/>
<!-- 連接有效性檢查的SQL -->
<property name="validationQuery" value="SELECT 1"/>
<!-- 連接有效性檢查的超時時間 1 秒 -->
<property name="validationQueryTimeout" value="1"/>
<!-- 周期性剔除長時間呆在池子里未被使用的空閑連接, 10秒一次-->
<property name="timeBetweenEvictionRunsMillis" value="10000"/>
<!-- 空閑多久可以認為是空閑太長而需要剔除 30 秒-->
<property name="minEvictableIdleTimeMillis" value="30000"/>
<!-- 是否緩存prepareStatement,也就是PSCache,MySQL建議關閉 -->
<property name="poolPreparedStatements" value="false"/>
<property name="maxOpenPreparedStatements" value="-1"/>
<!-- 是否設置自動提交,相當于每個語句一個事務 -->
<property name="defaultAutoCommit" value="true"/>
<!-- 記錄被判定為異常的連接 -->
<property name="logAbandoned" value="true"/>
<!-- 網絡讀取超時,網絡連接超時 -->
<property name="connectionProperties" value="connectTimeout=1000;socketTimeout=3000"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mybatis/mapper/*Mapper.xml"/>
<property name="typeAliasesPackage" value="org.learnjava.dq.core.dal.bean"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.learnjava.dq.core.dal.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean></beans>
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 激活自動代理功能 --> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- spring容器啟動時,靜態配置替換 --> <context:property-placeholder location="classpath*:*.properties" ignore-unresolvable="true"/> <context:component-scan base-package="org.learnjava.dq.core.dal.dao"/> <import resource="test-data-sources.xml"/></beans>
PS:這里我們只有一個DAO,所以spring容器加載就放在這個文件里了,如果DAO多的話,建議抽出一個BaseH2Test文件,這樣所有的DAO單元測試只需要加載一次spring容器。
package org.learnjava.dq.core.dal.dao;import org.junit.Test;import org.junit.runner.RunWith;import org.learnjava.dq.core.dal.bean.UserInfoBean;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.Date;import javax.annotation.Resource;import static org.junit.Assert.*;/**
* 作用:
* User: duqi
* Date: 2017/6/24
* Time: 09:33
*/@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:test-h3-applicationContext.xml")public class UserInfoDAOTest {
@Resource private UserInfoDAO userInfoDAO;
@Test public void saveUserInfoBean() throws Exception {
UserInfoBean userInfoBean = new UserInfoBean();
userInfoBean.setUserId(1003L);
userInfoBean.setNickname("wangwu");
userInfoBean.setMobile("18890987675");
userInfoBean.setSex(1);
userInfoBean.setUpdateTime(new Date());
userInfoBean.setCreateTime(new Date());
int rows = userInfoDAO.saveUserInfoBean(userInfoBean);
assertEquals(1, rows);
}
@Test public void updateUserInfoBean() throws Exception {
}
@Test public void getUserInfoBeanByUserId() throws Exception {
}
@Test public void getUserInfoBeanByMobile() throws Exception {
}
@Test public void listUserInfoBeanByUserIds() throws Exception {
}
@Test public void removeUserInfoBeanByUserId() throws Exception {
}}
Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with a clean & simple API. Mockito doesn’t give you hangover because the tests are very readable and they produce clean verification errors.
package org.learnjava.dq.biz.manager.impl;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.learnjava.dq.biz.domain.UserInfo;import org.learnjava.dq.biz.manager.UserInfoManager;import org.learnjava.dq.core.dal.bean.UserInfoBean;import org.learnjava.dq.core.dal.dao.UserInfoDAO;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.MockitoAnnotations;import org.mockito.runners.MockitoJUnitRunner;import static org.junit.Assert.*;import static org.mockito.Mockito.*;/**
* 作用:
* User: duqi
* Date: 2017/6/24
* Time: 09:55
*/@RunWith(MockitoJUnitRunner.class)public class UserInfoManagerImplTest {
@Mock //用于定義被Mock的組件
private UserInfoDAO userInfoDAO;
@InjectMocks //用于定義待測試的組件
private UserInfoManager userInfoManager = new UserInfoManagerImpl();
private UserInfo userInfoToSave;
@Before public void setUp() throws Exception {
//用于初始化@Mock注解修飾的組件
MockitoAnnotations.initMocks(this);
userInfoToSave = new UserInfo();
userInfoToSave.setMobile("18978760099");
userInfoToSave.setUserId(7777L);
userInfoToSave.setSex(1);
}
@Test public void saveUserInfo_case1() throws Exception {
//step1 準備數據和動作
doReturn(1).when(userInfoDAO).saveUserInfoBean(any(UserInfoBean.class));
//step2 運行待測試模塊
Boolean res = userInfoManager.saveUserInfo(userInfoToSave);
//step3 驗證測試結果
assertTrue(res);
}
@Test public void saveUserInfo_case2() throws Exception {
//step1 準備數據和動作
doReturn(0).when(userInfoDAO).saveUserInfoBean(any(UserInfoBean.class));
//step2 運行待測試模塊
Boolean res = userInfoManager.saveUserInfo(userInfoToSave);
//step3 驗證測試結果
assertFalse(res);
}
@Test public void updateUserInfo() throws Exception {
}
@Test public void getUserInfoByUserId() throws Exception {
}
@Test public void getUserInfoByMobile() throws Exception {
}
@Test public void listUserInfoByUserIds() throws Exception {
}
@Test public void removeUserInfoByUserId() throws Exception {
}}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。