Junit

   1 assertEquals,判断是否相等

assertEquals([String message], expected, actual);

 

assertEquals([String message], expected, actual, tolerance)
 

 

   2 assertNull,判断是否为Null

 

assertNull([String message], java.lang.Object object);
assertnotNull([String message], java.lang.Object object);

 

   3 assertSame,判断是否相同(指向同一对象)

 

assertSame([String message], expected, actual);
 
assertNotSame([String message], expected, actual);
 

 

   4 assertTrue,判断是否为true

 

assertTrue([String message], boolean condition);
 
assertFasle([String message], boolean conditon);
 

 

   5 fail,使测试立即失败

 

fail([String message]);
 

 

   6 Junit代码示例

package com.example.test;

import com.example.action.Largest;
import junit.framework.TestCase;

public class TestLargest extends TestCase {
    public TestLargest(String name){
        super(name);
    }

    public void testSimple(){
        assertEquals(9, Largest.largest(new int[] {7, 9, 8}));
    }

    public void testOrder() {
        assertEquals(9, Largest.largest(new int[] {9, 8, 7}));
        assertEquals(9, Largest.largest(new int[] {8, 9, 7}));
        assertEquals(9, Largest.largest(new int[] {7, 8, 9}));
    }

    public void testDups() {
        assertEquals(9, Largest.largest(new int[] {9, 8, 7, 9}));
    }

    public void testOne() {
        assertEquals(1, Largest.largest(new int[] {1}));
    }

    public void testNegative() {
        assertEquals(-7, Largest.largest(new int[] {-9, -8, -7}));
    }

    public void testEmpty() {
        try {
            Largest.largest(new int[] {});
            fail("Should have thrown an exception");
        } catch (RuntimeException e) {
            assertTrue(true);
        }
    }
}
  

 

   要点:

   (1)导入相关的junit包/类

   (2)测试类extends TestCase

   (3)定义测试类构造函数

 

public TestLargest(String name) {
   super(name);
}
   (4)定义其他测试方法,方法名常以test开始,方法中包含各种测试的断言(assert)。

 

 

   其他方法

   (1) setUp,在执行每个测试方法之前执行  

protected void setUp();

 

   (2)tearDown,在每个测试方法结束后执行

protected void tearDown();

  

   (3)oneTimeSetUp

public static void oneTimeSetUp() {

};

 

   (4)oneTimeTearDown

public static void oneTimeTearDown() {

};

 

   测试关键点:

  (1)边界

  (2)反向

  (3)交叉

  (4)错误条件

  (5)性能

 
 

你可能感兴趣的:(JUnit)