初步认识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) ...
随机推荐
- NET-SNMP配置
配置/etc/snmp/snmpd.conf such as below : ============================================== com2sec notCon ...
- android学习笔记52——手势Gesture,增加手势、识别手势
手势Gesture,增加手势 android除了提供了手势检测之外,还允许应用程序把用户手势(多个持续的触摸事件在屏幕上形成特定的形状)添加到指定文件中,以备以后使用 如果程序需要,当用户下次再次画出 ...
- phpstorm8.0汉化版下载
下载地址http://www.52z.com/soft/161911.html 汉化包:http://www.7down.net/soft/20586.html phpStorm汉化方法 1.安装原版 ...
- ios uiwebview 上几个技巧
以下内容转自 CrespoXiao的微博 分享个tips,阅读类app内容加载一般是本地存几个html框架,接口传body过来就行了,目的是节省流量.但是loadHTMLString在内容多尤其是图片 ...
- java 线程的使用
java 线程的使用 //线程的使用 //需要记三个单词 //1.Thread 线程的类名 //2. Runnable 线程的接口 //3. start 执行线程 //使用继承线程类的方式实现线程 c ...
- AsynTask用法
http://blog.csdn.net/liuhe688/article/details/6532519 在Android中实现异步任务机制有两种方式,Handler和AsyncTask. Hand ...
- 解决Tomcat catalina.out 不断成长导致档案过大的问题
Tomcat的网站上的说法http://wiki.apache.org/tomcat/FAQ/Logging#Q6: System.out 和 System.err 都被打印到 catalina.ou ...
- fgets读取文件时的注意事项
1 文本文件 a.txt 内容如下 2 c代码 FILE *fil; if (!(fil = fopen("/home/rudy/projects/paser/a.txt", &q ...
- 实用的VS工具
工具 1.Visual Studio Visual Studio Productivity Power tool:Visual Studio专业版(及以上)的扩展,具有丰富的功能,如快速查找,导航解决 ...
- (String)151. Reverse Words in a String
Given an input string, reverse the string word by word. For example,Given s = "the sky is blue& ...