初步认识JUnit
初步认识JUnit
目前大多数的基于Java的企业应用软件,肯定少不了单元测试,程序员通过编写单元测试来验证自己程序的有效性;管理者通过持续自动的执行单元测试和分析单元测试覆盖率来确保软件本身的质量。可以说单元测试和集成测试在软件开发整个流程中占有举足轻重的地位。
单元测试,是指对软件中的最小可测试单元进行检查和验证。单元测试不是为了证明程序是对的,而是证明程序没有错。Java常用的单元测试框架有JUnit,TestNG,还有些MOCK框架,这里我们只来讲述JUnit。
JUnit的两种版本是JUnit 3.8和JUnit 4,前者使用反射,后者使用反射和注解。
package com.shop.web.test;
public class Calculator {
private static double result = 0.0;
public void add(double num) {
result = result + num;
}
public void substract(double num) {
result = result - num;
}
public void multiply(double num) {
result = result * num;
}
public void divide(double num) {
if (num != 0) {
result = result / num;
} else {
result = result;
}
}
// 清零
public void clear() {
result = 0;
}
public double getResult() {
return result;
}
}
CalculatorTest.java
package com.shop.web.test;
import junit.framework.TestCase;
public class CalculatorTest extends TestCase {
private static Calculator calculator = new Calculator(); @Override
protected void setUp() throws Exception {
System.out.println("JUnit initialize the fixture state by overriding setup ");
calculator.clear();
}
@Override
protected void tearDown() throws Exception {
System.out.println("JUnit clean-up after a test by overriding tearDown ");
calculator.clear();
}
public void testAdd() {
System.out.println("add result:" + calculator.getResult());
calculator.add(10.1);
assertEquals(10.1, calculator.getResult());
}
public void testSubstract() {
System.out.println("substract result:" + calculator.getResult());
calculator.add(10.1);
calculator.substract(2);
assertEquals(8.1, calculator.getResult());
}
public void testMultiply() {
System.out.println("multiply result:" + calculator.getResult());
calculator.add(12);
calculator.multiply(12);
assertEquals(144.0, calculator.getResult());
}
public void testDivide() {
System.out.println("divide result:" + calculator.getResult());
calculator.add(12);
calculator.divide(12);
assertEquals(1.0, calculator.getResult());
}
}
绿条代表程序没有错误

public abstract class TestCase extends Assert implements Test
A test case defines the fixture to run multiple tests.
To define a test case
1) implement a subclass of TestCase
2) define instance variables that store the state of the fixture
3) initialize the fixture state by overriding setUp
4) clean-up after a test by overriding tearDown.
Each test runs in its own fixture so there can be no side effects among test runs
JUnit initialize the fixture state by overriding setup
add result:0.0
JUnit clean-up after a test by overriding tearDown
JUnit initialize the fixture state by overriding setup
substract result:0.0
JUnit clean-up after a test by overriding tearDown
JUnit initialize the fixture state by overriding setup
multiply result:0.0
JUnit clean-up after a test by overriding tearDown
JUnit initialize the fixture state by overriding setup
divide result:0.0
JUnit clean-up after a test by overriding tearDown
public class CalculatorTest4 {
private static Calculator calculator = new Calculator();
@Before
public void setUp() throws Exception {
System.out.println("JUnit initialize the fixture state by overriding setup ");
calculator.clear();
}
@After
public void tearDown() throws Exception {
System.out.println("JUnit clean-up after a test by overriding tearDown ");
calculator.clear();
}
@Test
public void add() {
System.out.println("add result:" + calculator.getResult());
calculator.add(10.1);
assertEquals(10.1, calculator.getResult());
}
4、@Test(expected=*.class)
在JUnit4.0之前,对错误的测试,我们只能通过fail来产生一个错误,并在try块里面assertTrue(true)来测试。现在,通过@Test元数据中的expected属性。expected属性的值是一个异常的类型,用来检查抛出预期异常。
@Test(expected=ArithmeticException.class)
public void divide(){
int i = 2/0;
}
5、@Test(timeout=xxx):
该元数据传入了一个时间(毫秒)给测试方法,
如果测试方法在制定的时间之内没有运行完,则测试也失败。
@Test(timeout=1)
public void count(){
for (int i = 0; i < 1000000000; i++) {
System.out.println(i);
}
}

该元数据标记的测试方法在测试中会被忽略。当测试的方法还没有实现,或者测试的方法已经过时,或者在某种条件下才能测试该方法(比如需要一个数据库联接, 而在本地测试的时候,数据库并没有连接),那么使用该标签来标示这个方法。同时,你可以为该标签传递一个String的参数,来表明为什么会忽略这个测试 方法。比如:@lgnore(“该方法还没有实现”),在执行的时候,仅会报告该方法没有实现,而不会运行测试方法。
@Ignore("此方法现在不需要")
@Test
public void ignore(){
System.out.println("不需要");
}
Spring整合JUnit
Junit测试Spring可以很方便的进行。
用到jar包:spring-test-xxx.jar,junit4的jar。
需要注解 @RunWith、@ContextConfiguration
@RunWith如: @RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner
@ContextConfiguration如: 用来加载Spring配置文件,@ContextConfiguration(locations = {"classpath:applicationContext-mybatis.xml",……"})
注意:(1)如果spring配置文件applicationContext.xml在classpath路径下,即通常的src目录下,这样加载配置文件,用classpath前缀。
(2)但是在web项目中,有些人喜欢把spring配置文件applicationContext.xml放在WEB-INF目录下,这里不是classpath目录。这种情况可以按如下方式配置:用file前缀,指定配置文件的绝对路径。貌似这种方式不是很友好。 如:locations = { "file:D:\\workspace\\webproxy\\src\\main\\resources\\" + "applicationContext.xml" }
完整代码如下:
package com.shop.web.test; import java.util.Date;
import java.util.List;
import java.util.UUID; import javax.annotation.Resource; import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSON;
import com.shop.web.entity.ShopUser;
import com.shop.web.service.ShopUserService;
import com.shop.web.util.DateUtil;
/**
* service、dao层的测试类
* @author ces
*
*/
@RunWith(SpringJUnit4ClassRunner.class)//表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = {"classpath:applicationContext-mybatis.xml","classpath:applicationContext-service.xml","classpath:applicationContext-transaction.xml"})
public class ShopControllerTest { private static Logger logger = Logger.getLogger(ShopControllerTest.class); @Resource
private ShopUserService shopUserService; @Transactional
@Test
public void getShopUserById(){
ShopUser shopUser = new ShopUser();
shopUser.setUserid();
shopUser.setUsername("zhangsan");
shopUser.setPassword("");
shopUser.setCreateTime(Long.parseLong(DateUtil.getString(new Date(), DateUtil.YMDHMS)));
try {
shopUserService.insertSelective(shopUser);
int i = /;
} catch (Exception e) {
e.printStackTrace();
logger.info("ShopControllerTest" + e);
} logger.info(JSON.toJSONString("*********"));
}
}
初步认识JUnit的更多相关文章
- 个人项目(JUnit单元测试)
---恢复内容开始--- 一. 题目简介 这次的单元测试我选择作了一个基本运算的程序,该程序实现了加,减,乘,除,平方,倒数的运算,该程序进行测试比较的简单,对于初步接触JUn ...
- Java单元测试之JUnit 5快速上手
前言 单元测试是软件开发中必不可少的一环,但是在平常开发中往往因为项目周期紧,工作量大而被选择忽略,这样往往导致软件问题层出不穷.线上出现的不少问题其实在有单元测试的情况下就可以及时发现和处理,因此培 ...
- JUnit4 单元测试
一. 题目简介 这次的单元测试我作了一个基本运算的程序,该程序实现了加,减,乘,除,平方,倒数的运算,该程序进行测试比较的简单,对于初步接触JUnit的我来说测试起来也比较容易理解. 二.源码的git ...
- 关于初步搭建完成SSH环境之后,JUnit test 测试成功,页面测试时:@Resource 注入的dao为null
这个问题研究了一天,还是因为配置的时候没有认真,一不小心,酿成了大错.当发现的时候感觉好尴尬啊::>_<:: CostAction: package com.tenni.action; i ...
- [Java] Spring + SpringMVC + Maven + JUnit 搭建
示例项目下载: https://github.com/yangyxd/SpringDemo 利用前面 SpringMVC 项目的配置方式,完成初步的项目创建.下面只讲一些不同之处. 传送门: [Jav ...
- Dagger2 使用初步
Dagger2 是一个Android依赖注入框架,由谷歌开发,最早的版本Dagger1 由Square公司开发.依赖注入框架主要用于模块间解耦,提高代码的健壮性和可维护性.Dagger 这个库的取名不 ...
- 搜索引擎系列 ---lucene简介 创建索引和搜索初步
一.什么是Lucene? Lucene最初是由Doug Cutting开发的,2000年3月,发布第一个版本,是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎 :Lucene得名于Doug妻子 ...
- junit浅学笔记
JUnit是一个回归测试框架(regression testing framework).Junit测试是程序员测试,即所谓白盒测试,因为程序员知道被测试的软件如何(How)完成功能和完成什么样(Wh ...
- JUnit学习总结
Junit简介: Junit最初是由Erich Gamma 和 Kent Beck 编写的一个回归测试框架(regression testing framework),为单元测试(Unit Test) ...
随机推荐
- .net4缓存笔记
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- python---字符编码
获取系统默认字符编码 在Python代码中,普通字符串的编码方式与程序源文件编码方式一致的,而很多IDE在默认情况下,将程序源文件按照系统默认字符编码来保存的. 下面给出用Python获取系统默认编码 ...
- SQL Server 2012 配置数据库邮件
发送和接受邮箱不能用QQ邮箱,可以用163网易邮箱,同时要求要发送邮件的计算机能上外网 查看163网易邮箱的发送和接收服务器的方法如下 在数据库的管理中,右击数据库邮件,选择配置数据库邮件 出现对话框 ...
- Asp.net MVC 视图引擎
Asp.net MVC视图引擎有两种: 1.ASPX View Engine 这个做过WebForm的人都清楚 设计目标:一个用于呈现Web Form页面的输出的视图引擎. 2.Razor View ...
- [Tex学习]WinEdit 常用软件快捷键
WinEdit 常用软件快捷键 编辑: Alt+C:在剪贴板原有复制文本后增加新的被选择的文本. Ctrl+Shift+Alt+Right/Left:对选中文本增加或者删除Comment标记. Ctr ...
- youtube不显示其他人头像
我用的是ss , 右键ss选择pac->编辑本地pac 把ggpht.com加入pac列表即可
- Linux卷配置管理
[root@linux ~]# df -hFilesystem Size Used Avail Use% Mounted on/dev/sda3 19G 11G 6.5G 63% /tmpfs 995 ...
- 如何用pdb进行python调试
本文章讲述了如何用pdb进行python调试讲解. 当手边 没有IDE,面对着python调试犯愁时,你就可以参考下本文;(pdb 命令调试) 参 考:http://docs.python.org/l ...
- 【知识点】业务连接服务(BCS)认证概念整理
业务连接服务(BCS)认证概念整理 I. BDC认证模型 BDC服务支持两种认证模型:信任的子系统,模拟和代理. 在信任的子系统模型中,中间层(通常是Web服务器)通过一个固定的身份来向后端服务器取得 ...
- 用递归方法求一个list的最大值
极好的一张图,瞬间理解.然后留意一下边界条件直接搞定.