1. 程式人生 > >斷言方法(Assert Methods)

斷言方法(Assert Methods)

Junit 4 斷言方法允許檢查測試方法的期望結果值和真實返回值。Junit的org.junit.Assert類提供了各種斷言方法來寫junit測試。這些方法被用來檢查方法的真實結果值和期望值。下列一些有用的斷言方法列表:

Junit 4 Assert Methods
Method Description
assertNull(java.lang.Object object) 檢查物件是否為空
assertNotNull(java.lang.Object object) 檢查物件是否不為空
assertEquals(long expected, long actual) 檢查long型別的值是否相等
assertEquals(double expected, double actual, double delta) 檢查指定精度的double值是否相等
assertFalse(boolean condition) 檢查條件是否為假
assertTrue(boolean condition) 檢查條件是否為真
assertSame(java.lang.Object expected, java.lang.Object actual) 檢查兩個物件引用是否引用同一物件(即物件是否相等)
assertNotSame(java.lang.Object unexpected, java.lang.Object actual)

檢查兩個物件引用是否不引用統一物件(即物件不等)

 Junit 4斷言方法樣例

AssertionsTest.java junit測試用例,顯示各種斷言方法:

import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
 
/**
 * @author javatutorials.co.in
 */
public class AssertionsTest {
 
    @Test
    public void testAssertNull() {
        String str = null;
        assertNull(str);
    }
 
    @Test
    public void testAssertNotNull() {
        String str = "hello Java!!";
        assertNotNull(str);
    }
 
    @Test
    public void testAssertEqualsLong() {
        long long1 = 2;
        long long2 = 2;
        assertEquals(long1, long2);
    }
 
    @Test
    public void testAssertEqualsDouble() {
        // test case is successfull as double1 and double 2
        // differ by 0.001 which is less than our specified delta
        double double1 = 1.236;
        double double2 = 1.237;
        double delta = 0.002;
        assertEquals(double1, double2, delta);
    }
 
    @Test
    public void testAssertTrue() {
        List<String> list = new ArrayList<String>();
        assertTrue(list.isEmpty());
    }
 
    @Test
    public void testAssertFalse() {
        List<String> list = new ArrayList<String>();
        list.add("hello");
        assertFalse(list.isEmpty());
    }
 
    @Test
    public void testAssertSame() {
        String str1 = "hello world!!";
        String str2 = "hello world!!";
        assertSame(str2, str1);
    }
 
    @Test
    public void testAssertNotSame() {
        String str1 = "hello world!!";
        String str3 = "hello Java!!";
        assertNotSame(str1, str3);
    }
}

樣例輸出

在eclipse Junit 視窗的輸出如下:

本文出處為 http://blog.csdn.net/luanlouis,轉載請註明出處,謝謝!