Junit的使用

对计算器进行单元测试

 

package com.anllin.junit;

 

public class Calculator

{

    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 devide(int a, int b) throws Exception

    {

       if(0 == b)

       {

           throw new Exception("can't devide by zero");

       }

       return a / b;

    }

}

 

 

写测试用例的一些最基本的要求。

package com.anllin.junit;

 

import junit.framework.Assert;

import junit.framework.TestCase;

 

/**

 *

 * 测试类必须继承于TestCase

 *

 * junit3.8中,测试方法需要满足如下原则:

 *

 * 1.public

 * 2.void

 *  3.无方法参数

 *  4.方法名称必须以test开头的

 */

public class CalculatorTest extends TestCase

{

    private int a;

    private int b;

   

    private Calculator calc;

   

    public CalculatorTest(String name)

    {

       super(name);

    }

 

    //每个测试用例执行之前执行

    @Override

    protected void setUp() throws Exception

    {

       a = 1;

       b = 2;

      

       calc = new Calculator();

    }

   

    //每个测试用例执行完成之后执行

    @Override

    protected void tearDown() throws Exception

    {

      

    }

   

    public void testAdd()

    {

       try

       {

           Thread.sleep(500);

       }

       catch (InterruptedException e)

       {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

       int actual = calc.add(a,b);

       int expected = 3;

       Assert.assertEquals(expected,actual);

    }

   

    public void testSubtract()

    {

       int actual = calc.subtract(a,b);

       int expected = -1;

       Assert.assertEquals(expected,actual);

    }

   

    public void testMultiply()

    {

       int actual = calc.multiply(a,b);

       int expected = 2;

       Assert.assertEquals(expected,actual);

    }

   

    public void testDevide()

    {

       int actual = 0;

       try

       {

           actual = calc.devide(a,b);

       }

       catch (Exception e)

       {

           e.printStackTrace();

           Assert.fail();

       }

       int expected = 0;

       Assert.assertEquals(expected,actual);

    }

   

    public void testDevideByZero()

    {

       Exception tx = null;

 

       try

       {

           calc.devide(a,0);

           Assert.fail("test failed");

       }

       catch (Exception e)

       {

           tx = e;

       }

      

       Assert.assertEquals(Exception.class,tx.getClass());

       Assert.assertEquals("can't devide by zero",tx.getMessage());

    }

   

    public static void main(String[] args)

    {

       //用控制台输出方式运行测试

       junit.textui.TestRunner.run(CalculatorTest.class);

       junit.awtui.TestRunner.run(CalculatorTest.class);

       junit.swingui.TestRunner.run(CalculatorTest.class);

    }

}

 

 

 

对类中私有方法进行单元测试 

 

package com.anllin.junit;

 

public class Calc2

{

    @SuppressWarnings("unused")

    private int add(int a, int b)

    {

       return a + b;

    }

}

 

必须使用反射才能访问私有方法或变量

package com.anllin.junit;

 

import java.lang.reflect.Method;

 

import junit.framework.Assert;

import junit.framework.TestCase;

 

public class Calc2Test extends TestCase

{

    public void testAdd()

    {

       try

       {

           Calc2 calc = new Calc2();

          

           Class<Calc2> classType = Calc2.class;

          

           Method method = classType.getDeclaredMethod("add",new Class[]{Integer.TYPE,Integer.TYPE});

          

           method.setAccessible(true);

          

           Object result = method.invoke(calc,new Object[]{2,3});

          

           Assert.assertEquals(5,result);

       }

       catch (Exception e)

       {

           Assert.fail();

       }

    }

}

 

 

 

测试获取最大整数类

package com.anllin.junit;

 

public class Largest

{

    public int getLargest(int[] arr) throws Exception

    {

       if(null == arr || 0 == arr.length)

       {

           throw new Exception("数据不能为空");

       }

      

       int result = arr[0];

      

       for(int i=0;i<arr.length;i++)

       {

           if(result < arr[i])

           {

              result= arr[i];

           }

       }

      

       return result;

    }

}

 

测试用例可能比类方法多,这是正常的,对于各种情况都要考虑到。包括正常的,不正常的。

Package com.anllin.junit;

 

import junit.framework.Assert;

import junit.framework.TestCase;

 

public class LargestTest extends TestCase

{

    private Largest largest;

   

    @Override

    protected void setUp() throws Exception

    {

       largest = new Largest();

    }

   

    public void testGetLargest()

    {

       int[] arr = {1,9,-10,-20,23,24};

      

       int result= 0;

      

       try

       {

           result = largest.getLargest(arr);

       }

       catch (Exception e)

       {

           Assert.fail("test failed");

       }

      

       Assert.assertEquals(24,result);

    }

   

    public void testGetLargest2()

    {

       Exception tx = null;

       int[] arr = {};

      

       try

       {

           largest.getLargest(arr);

           Assert.fail("test failed");

       }

       catch (Exception e)

       {

           tx = e;

       }

      

       Assert.assertNotNull(tx);

      

       Assert.assertEquals(Exception.class,tx.getClass());

      

       Assert.assertEquals("数据不能为空",tx.getMessage());

    }

   

    public void testGetLargest3()

    {

       Exception tx = null;

       int[] arr = null;

      

       try

       {

           largest.getLargest(arr);

           Assert.fail("test failed");

       }

       catch (Exception e)

       {

           tx = e;

       }

      

       Assert.assertNotNull(tx);

      

       Assert.assertEquals(Exception.class,tx.getClass());

      

       Assert.assertEquals("数据不能为空",tx.getMessage());

    }

}

 

 

 

对自定义类的方法进行测试

package com.anllin.junit;

 

public class MyStack

{

    String[] elements;

 

    int index;

 

    public MyStack()

    {

       elements = new String[100];

       index = 0;

    }

 

    public void push(String element) throws Exception

    {

       if ("".equals(element) || null == element)

       {

           throw new Exception("The parameter can't be null");

       }

       if (100 == index)

       {

           throw new Exception("out of range to array");

       }

       elements[index++] = element;

    }

 

    public String pop() throws Exception

    {

       if (0 == index)

       {

           throw new Exception("out of range to array");

       }

 

       return elements[--index];

    }

 

    public String top() throws Exception

    {

       if (0 == index)

       {

           throw new Exception("out of range to array");

       }

 

       return elements[index - 1];

    }

 

    public void delete(int n) throws Exception

    {

       if (index - n < 0)

       {

           throw new Exception("out of range to array");

       }

 

       index -= n;

    }

}

 

 

 

package com.anllin.junit;

 

import junit.framework.Assert;

import junit.framework.TestCase;

 

public class MyStackTest extends TestCase

{

    private MyStack stack;

 

    @Override

    protected void setUp() throws Exception

    {

       stack = new MyStack();

    }

 

    public void testPush()

    {

       try

       {

           stack.push("hello");

       }

       catch (Exception e)

       {

           Assert.fail("test failed");

       }

 

       String result = null;

 

       try

       {

           result = stack.pop();

       }

       catch (Exception e)

       {

           Assert.fail("test failed");

       }

 

       Assert.assertEquals("hello", result);

    }

 

    public void testPush2()

    {

       for (int i = 0; i < 100; i++)

       {

           try

           {

              stack.push(i + "");

           }

           catch (Exception e)

           {

              Assert.fail("test failed");

           }

       }

 

       for (int i = 0; i < 100; i++)

       {

           String result = null;

           try

           {

              result = stack.pop();

           }

           catch (Exception e)

           {

              Assert.fail("test failed");

           }

 

           Assert.assertEquals((99 - i) + "", result);

       }

    }

 

    public void testPush3()

    {

       Exception tx = null;

 

       try

       {

           for (int i = 0; i < 101; i++)

           {

              stack.push(i + "");

           }

 

           Assert.fail();

       }

       catch (Exception e)

       {

           tx = e;

       }

 

       Assert.assertNotNull(tx);

       Assert.assertEquals(Exception.class, tx.getClass());

       Assert.assertEquals("out of range to array", tx.getMessage());

    }

 

    public void testPop1()

    {

       try

       {

           stack.push("hello");

       }

       catch (Exception e)

       {

           Assert.fail("test failed");

       }

 

       String result = null;

 

       try

       {

           result = stack.pop();

       }

       catch (Exception e)

       {

           Assert.fail("test failed");

       }

 

       Assert.assertEquals("hello", result);

    }

 

    public void testPop2()

    {

       Exception tx = null;

 

       try

       {

           stack.pop();

 

           Assert.fail();

       }

       catch (Exception e)

       {

           tx = e;

       }

 

       Assert.assertNotNull(tx);

       Assert.assertEquals(Exception.class, tx.getClass());

       Assert.assertEquals("out of range to array", tx.getMessage());

    }

 

    public void testPop3()

    {

       Exception tx = null;

 

       try

       {

           stack.push("hello");

       }

       catch (Exception e)

       {

           Assert.fail("test failed");

       }

 

       try

       {

           stack.pop();

           stack.pop();

           Assert.fail();

       }

       catch (Exception e)

       {

           tx = e;

       }

 

       Assert.assertNotNull(tx);

       Assert.assertEquals(Exception.class, tx.getClass());

       Assert.assertEquals("out of range to array", tx.getMessage());

    }

 

    public void testTop()

    {

       try

       {

           stack.push("hello");

       }

       catch (Exception e)

       {

           Assert.fail("test failed");

       }

 

        String result = null;

 

       try

       {

           result = stack.top();

       }

       catch (Exception e)

       {

           Assert.fail("test failed");

       }

 

       Assert.assertEquals("hello", result);

    }

 

    public void testTop2()

    {

       Exception tx = null;

 

       try

       {

           stack.top();

           Assert.fail("test failed");

       }

       catch (Exception e)

       {

           tx = e;

       }

 

       Assert.assertNotNull(tx);

       Assert.assertEquals(Exception.class, tx.getClass());

       Assert.assertEquals("out of range to array", tx.getMessage());

    }

   

    public void testDelete()

    {

       try

        {

           for(int i= 0;i<10;i++)

           {

              stack.push(i+"");

           }

           stack.delete(10);

       }

       catch (Exception e)

       {

           Assert.fail();

       }

    }

   

    public void testDelete2()

    {

       Exception tx = null;

 

       try

       {

           for(int i= 0;i<10;i++)

           {

              stack.push(i+"");

           }

           stack.delete(11);

          

           Assert.fail("test failed");

       }

       catch (Exception e)

       {

           tx = e;

       }

 

       Assert.assertNotNull(tx);

       Assert.assertEquals(Exception.class, tx.getClass());

       Assert.assertEquals("out of range to array", tx.getMessage());

    }

}

 

 

 

对文件删除操作进行单元测试

package com.anllin.junit;

 

import java.io.File;

 

public class FileTest8

{

    public static void deleteAll(File file)

    {

       if(file.isFile() || 0 == file.list().length)

       {

           file.delete();

       }

       else

       {

           File[] files = file.listFiles();

          

           for(File f : files)

           {

              deleteAll(f);

              f.delete();

           }

       }

    }

}

 

 

测试前是什么样子,测试后就应该是什么样子,不能因为测试而导致文件的改变

package com.anllin.junit;

 

import java.io.File;

 

import junit.framework.Assert;

import junit.framework.TestCase;

 

public class DeleteAllTest extends TestCase

{

    private File file = null;

   

    public void testDeleteAll()

    {

       try

       {

           file = new File("text.txt");

           file.createNewFile();

           FileTest8.deleteAll(file);

       }

       catch (Exception e)

       {

           Assert.fail();

       }

      

       boolean isExist = file.exists();

      

       Assert.assertFalse(isExist);

    }

   

    /**

     * Diretory tree

     *

     * dir--|

     *      |--f1.txt

     *      |--f2.txt

     *      |--d1

     *         |--f5.txt

     *      |--d2

     *         |--f6.txt 

     */

    public void testDeleteAll2()

    {

       try

       {

           file = new File("dir");

           file.mkdir();

          

           File file1 = new File(file,"f1.txt");

           File file2 = new File(file,"f2.txt");

          

           file1.createNewFile();

           file2.createNewFile();

          

           File d1 = new File(file,"d1");

           File d2 = new File(file,"d2");

          

           d1.mkdir();

           d2.mkdir();

          

           File file5 = new File(d1,"f5.txt");

           File file6 = new File(d2,"f6.txt");

          

           file5.createNewFile();

           file6.createNewFile();

          

           FileTest8.deleteAll(file);

       }

       catch (Exception e)

       {

           Assert.fail();

       }

      

       Assert.assertNotNull(file);

       String[] names = file.list();

       Assert.assertEquals(0,names.length);

      

       file.delete();

    }

}

 

 

 

测试套件的使用

package com.anllin.junit;

 

import junit.extensions.RepeatedTest;

import junit.framework.Test;

import junit.framework.TestCase;

import junit.framework.TestSuite;

 

public class TestAll extends TestCase

{

    public static Test suite()

    {

       TestSuite suite = new TestSuite();

      

       suite.addTestSuite(CalculatorTest.class);

       suite.addTestSuite(DeleteAllTest.class);

       suite.addTestSuite(Calc2Test.class);

       suite.addTestSuite(LargestTest.class);

       suite.addTestSuite(MyStackTest.class);

      

       suite.addTest(new RepeatedTest(new CalculatorTest("testSubtract"),20));

      

      

       return suite;

    }

}

 

 

 

 

 

 

 

 

Junit4.0的使用

 

对计算器类进行测试

package com.anllin.junit;

 

import static org.junit.Assert.assertEquals;

import static org.junit.Assert.fail;

 

import org.junit.After;

import org.junit.AfterClass;

import org.junit.Before;

import org.junit.BeforeClass;

import org.junit.Test;

 

public class CalculatorTest

{

    private int a;

    private int b;

   

    private Calculator calc;

   

    @BeforeClass

    public static void globalInit()

    {

       System.out.println("globalInit invoked");

    }

   

    @AfterClass

    public static void globalDestroy()

    {

       System.out.println("globalDestroy invoked");

    }

   

    @Before

    public void setUp() throws Exception

    {

       a = 1;

       b = 2;

      

       calc = new Calculator();

       System.out.println("setUp invoked");

    }

 

    @After

    public void tearDown() throws Exception

    {

       System.out.println("tearDown invoked");

    }

 

    @Test(timeout=200)

    public void testAdd()

    {

       int actual = calc.add(a,b);

       int expected = 3;

       assertEquals(expected,actual);

    }

 

    @Test

    public void testSubtract()

    {

       int actual = calc.subtract(a,b);

       int expected = -1;

       assertEquals(expected,actual);

    }

 

    @Test

    public void testMultiply()

    {

       int actual = calc.multiply(a,b);

       int expected = 2;

       assertEquals(expected,actual);

    }

 

    @Test

    public void testDevide()

    {

       int actual = 0;

       try

       {

           actual = calc.devide(a,b);

       }

       catch (Exception e)

       {

           e.printStackTrace();

           fail();

       }

       int expected = 0;

       assertEquals(expected,actual);

    }

 

    @Test

    public void testDevideByZero()

    {

       Exception tx = null;

 

       try

       {

           calc.devide(a,0);

           fail("test failed");

       }

       catch (Exception e)

       {

           tx = e;

       }

      

       assertEquals(Exception.class,tx.getClass());

       assertEquals("can't devide by zero",tx.getMessage());

    }

   

    @Test(expected=Exception.class)

    public void testDevideByZero2() throws Exception

    {

       calc.devide(a,0);

    }

   

    public static void main(String[] args)

    {

       //用控制台输出方式运行测试

       //junit.textui.TestRunner.run(CalculatorTest.class);

       //junit.awtui.TestRunner.run(CalculatorTest.class);

    }

}

 

 

 

对取最大整数进行测试

 

package com.anllin.junit;

 

import static org.junit.Assert.assertEquals;

import static org.junit.Assert.fail;

 

import org.junit.After;

import org.junit.Before;

import org.junit.Ignore;

import org.junit.Test;

 

public class LargestTest

{

    private Largest largest;

 

    @Before

    public void setUp() throws Exception

    {

       largest = new Largest();

    }

 

    @After

    public void tearDown() throws Exception

    {

    }

 

    @Test

    public void testGetLargest()

    {

       int[] arr = { 1, 9, -10, -20, 23, 24 };

 

       int result = 0;

 

       try

       {

           result = largest.getLargest(arr);

       }

       catch (Exception e)

        {

           fail("test failed");

       }

 

       assertEquals(24, result);

    }

 

    @Test(expected = Exception.class)

    public void testGetLargest2() throws Exception

    {

       largest.getLargest(null);

    }

 

    @Test(expected = Exception.class)

    @Ignore("not ready yet")//表示忽略这个方法,测试运行时不会被执行

    public void testGetLargest3() throws Exception

    {

       largest.getLargest(new int[] {});

    }

 

}

 

 

 

参数化测试

package com.anllin.junit;

 

import static org.junit.Assert.*;

 

import java.util.Arrays;

import java.util.Collection;

 

import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.junit.runners.Parameterized;

import org.junit.runners.Parameterized.Parameters;

/**

 * 参数化测试

 *

 * @author anllin

 *

 */

@RunWith(Parameterized.class)

public class ParameteredTest

{

    private int expected;

 

    private int input1;

 

    private int input2;

 

    private Calculator calc;

 

    @Before

    public void setUp()

    {

       calc = new Calculator();

    }

 

    @SuppressWarnings({"rawtypes" })

    @Parameters

    public static Collection prepareData()

    {

       Object[][] object = { { 3, 1, 2 }, { -4, -1, -3 }, { 5, 2, 3 },

              { 4, -4, 8 } };

 

       return Arrays.asList(object);

    }

 

    public ParameteredTest(int excepted, int input1, int input2)

    {

       this.expected = excepted;

       this.input1 = input1;

       this.input2 = input2;

 

    }

 

    @Test

    public void testAdd()

    {

       assertEquals(this.expected, calc.add(input1, input2));

    }

 

}

 

 

 

测试套件的使用

package com.anllin.junit;

 

import org.junit.runner.RunWith;

import org.junit.runners.Suite;

 

//测试套件的使用

@RunWith(Suite.class)

@Suite.SuiteClasses({ CalculatorTest.class, LargestTest.class,ParameteredTest.class })

public class TestAll

{

 

}

 

 

把另一个测试套件作为这个测试套件的一部分

package com.anllin.junit;

import org.junit.runner.RunWith;

import org.junit.runners.Suite;

 

//把另一个测试套件作为这个测试套件的一部分

@RunWith(Suite.class)

@Suite.SuiteClasses({ TestAll.class })

public class TestAll2

{

   

}

 

 

posted @ 2011-08-17 22:55  水之原  阅读(804)  评论(0编辑  收藏  举报