微信公众号【黄小斜】大厂程序员,互联网行业新知,终身学习践行者。关注后回复「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 {
}}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:http://blog.itpub.net/69906029/viewspace-2653963/