初步认识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) ...
随机推荐
- MySQL存储过程调试工具-dbForge Studio for MySQL
工具官网地址:http://www.devart.com/dbforge/mysql/studio/ 对于某些存储过程很多且复杂的SQL的应用,在短时间内要使得所有MySQL存储过程和函数正常运行,那 ...
- knockout 第一个实例visible
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- 【AT91SAM3S】建立基于SAM3S库的工程并点亮LED
习惯了ST的库,猛然间看到ATMEL的库,有点无从下手.这几天参考这示例工程,终于建立了一个使用ATMEl库的工程. 软件库版本: 软件平台:MDK470A 硬件平台:英蓓特 EB-SAM3S MCU ...
- Yii里表单的操作方法(展示渲染待续......)
<?php$form=\yii\widgets\ActiveForm::begin(['action'=>\yii\helpers\Url::to('name/create')]);ech ...
- CORBA GIOP消息格式学习
想要深入理解ORB的工作过程与原理,学习与了解GIOP消息格式必不可少.我们知道GIOP是独立于具体通信的更高级别的抽象,因此这里针对GIOP在TCP/IP上的实现IIOP协议进行学习与分析(IIOP ...
- 查看并更改mysql编码
show variables like 'character%'; set character_set_client=utf8 ; set character_set_connection=utf8 ...
- 欧几里得&扩展欧几里得
原博网址:http://www.cnblogs.com/frog112111/archive/2012/08/19/2646012.html 欧几里德算法 欧几里德算法又称辗转相除法,用于计算两个整数 ...
- 56. Edit Distance && Simplify Path
Edit Distance Given two words word1 and word2, find the minimum number of steps required to convert ...
- Java正则表达式详解
转自http://edu.yesky.com/edupxpt/18/2143018.shtml
- 解决【win10管理员已阻止程序运行】问题时有感
今天在安装loadrunner11的时候点击setup弹出以下报错 然后试了很多方法,从网上找了各种解决方案:修改UAC.修改本地组策略,均未解决ps:本人电脑是win10家庭中文版. 研究了半天未果 ...