下载JUnit.jar和hamcrest.jar
许多IDE都自带了JUnit,但是并不推荐使用, 我们自己动手下载Jar包(不推荐使用的原因后面会说明)
点击http://www.junit.org可以下载到最新版本的JUnit,目前最新版本是4.11。进入官网选择Download and Install guide,
然后选择Plain-old JAR下的junit.jar,找到最新的4.11版本,下载jar包.
点击http://code.google.com/p/hamcrest/downloads/list下载最新的hamcrest-1.3.zip,解压.找到hamcrest-core-1.3.jar
然后在项目中引用junit-4.11.jar和hamcrest-core-1.3.jar,这样你就可以使用JUnit编写单元测试代码了.
三、简单的例子
记得在几乎每本语言教学书上都能找到HelloWorld这个入门代码。今天在这里,我们也从一个简单到根本不用单元测试的例子入手。四则运算。
第一步:建立项目引用junit-4.11.jar和hamcrest-core-1.3.jar
第二步:编写Calculator类,代码如下:
-
- public class Calculator {
-
- public int plus(int x, int y) {
- return x + y;
- }
-
- public int subtraction(int x, int y) {
- return x - y;
- }
-
- public int multiplication(int x, int y) {
- return x * y;
- }
-
- public int division(int x, int y) {
- return x / y;
- }
-
- }
第三步:编写单元测试类,代码如下:
-
-
- import static org.junit.Assert.*;
-
- import org.junit.Ignore;
- import org.junit.Test;
-
-
- public class TestCalculator {
-
- @Test
- public void testPlus() {
- Calculator cal = new Calculator();
- assertEquals(cal.plus(5, 5), 10);
- }
-
- @Test
- public void testSubtraction() {
- Calculator cal = new Calculator();
- assertEquals(cal.subtraction(5, 5), 0);
- }
-
- @Ignore
- @Test
- public void testMultiplication() {
- Calculator cal = new Calculator();
- assertTrue(cal.multiplication(5, 5) > 20);
- }
-
- @Test(expected = java.lang.ArithmeticException.class, timeout = 50)
- public void testDivision() {
- Calculator cal = new Calculator();
- assertEquals(cal.division(8, 0), 4);
- }
- }
第四步:测试,在这里,我用的是MyEclipse,在TestCalculator类上右键找到Run As 下的JUnit Test,点击然后就开始测试了
第五步:观察测试结果,在这里我测试都是正确的,
但是每个测试方法下都new一个Calculator对象很浪费资源,假如有80个测试方法呢?所以接下来我们要使用@BeforeClass,代码如下:
-
- import static org.junit.Assert.*;
-
- import org.junit.BeforeClass;
- import org.junit.Ignore;
- import org.junit.Test;
-
- import com.zjw.junit4.Calculator;
-
- public class TestCalculator {
-
- private static Calculator cal;
-
- @BeforeClass
- public static void beforeClass(){
- cal=new Calculator();
- }
-
- @Test
- public void testPlus() {
- assertEquals(cal.plus(5, 5), 10);
- }
-
- @Test
- public void testSubtraction() {
- assertEquals(cal.subtraction(5, 5), 0);
- }
-
- @Ignore
- @Test
- public void testMultiplication() {
- assertTrue(cal.multiplication(5, 5) > 20);
- }
-
- @Test(expected = java.lang.ArithmeticException.class, timeout = 50)
- public void testDivision() {
- assertEquals(cal.division(8, 0), 4);
- }
- }