使用Junit測試


一套測試就是一個強大的bug偵測器,能夠大大的縮短查找bug的時間。

本次我們主要了解使用Junit對代碼進行測試。

Junit中有以下這些方法可以對結果進行判定:

assertArrayEquals(expecteds, actuals) 查看兩個數組是否相等。
assertEquals(expected, actual) 查看兩個對象是否相等。類似於字符串比較使用的equals()方法
assertNotEquals(first, second) 查看兩個對象是否不相等。
assertNull(object) 查看對象是否為空。
assertNotNull(object) 查看對象是否不為空。
assertSame(expected, actual) 查看兩個對象的引用是否相等。類似於使用“==”比較兩個對象
assertNotSame(unexpected, actual) 查看兩個對象的引用是否不相等。類似於使用“!=”比較兩個對象
assertTrue(condition) 查看運行結果是否為true。
assertFalse(condition) 查看運行結果是否為false。
assertThat(actual, matcher) 查看實際值是否滿足指定的條件
fail() 讓測試失敗

現在我們來測試文件讀取器FileReader

第一步:准備一個測試文件read,可以是任意格式的文件,內容如下:

Lily 1 90 80 72
Jack 2 88 91 80
Peter 3 69 93 70

第二步:創建一個測試類TestFileReader

package File;
import static org.junit.Assert.*;

import java.io.FileReader;
import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestFileReader {
}

第三步:添加setUp和tearDown方法

setup用於產生文件讀取對象,teardown用於刪除文件對象,因為Java中有自帶的垃圾回收處理機制,所以不需要額外的刪除對象,在這里我們使用teardown用來關閉文件。

public class TestFileReader {
    FileReader _input;
    
    @Before
    public void setUp() throws Exception {
        try {
            _input = new FileReader("E:/code/Rent/src/File/read");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("file can't open");
        }
    }

    @After
    public void tearDown() throws Exception {
        try {
            _input.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("file can't close");
        }
    }
}
setUp&&tearDown

第四步:添加測試代碼

        @Test
    public void testRead() throws IOException {
        char ch='&';
        for(int i = 0; i < 3; i++){
            ch = (char) this._input.read();
        }
        assertEquals(ch,'l');
    }
    
    @Test
    public void testReadAtEnd() throws IOException{
        int ch = -111111;
        for(int i = 0; i < 53; i++){
            ch = this._input.read();
        }
        assertEquals(ch,-1);
    }    
Test Code

注意:我們這里使用的是junit4,不是junit3.junit4比junit3更加方便簡潔。

這里我們就微微的介紹一下junit4和junit3的不同。以及junit4的用法

不同:

1)junit4最大的特點就是引入了注釋,通過注釋來執行代碼。如:在setUp函數之上加before就是先執行,在tearDown上after就是后執行,在測試代碼上加test就是表示是測試代碼。不用再根據命名來執行。

2)junit4不需要繼承testcase類

3)集成測試時,直接在類之上注釋添加加入的單元測試

@RunWith(Suite.class)

@Suite.SuiteClasses({ TestCase1.class, TestCase2.class })

4)測試異常時,junit3是使用try-catch在異常之后添加fail。junit4添加@Test,使用參數“expected”,並指明拋出異常的Exception類:

//越界異常
@Test(expected = IndexOutOfBoundsException.class ) 
public void testCase2() {         
        /* test case 2*/          
        ArrayList emptyList = new ArrayList();    
        Object o = emptyList.get(0);    
}

5)設置超時,junit4使用"timeout"參數。如果測試運行的時間超過指定的毫秒數,則測試失敗。

@Test(timeout=3000) 
public void remoteBaseRelativeResolutionWithDirectory()    
 throws IOException, ParsingException { 
  readBuilder.parse("config.xml" );    
}

6)運行測試類,junit4不需要添加main函數,直接運行junit即可

7)參數化測試,junit4中的測試類不再使用構造函數添加參數,而是只寫一個測試函數,把這若干種情況作為參數傳遞進去,一次性的完成測試。在測試類的上面加@RunWith(Parameterized.class)

@RunWith(Parameterized.class)
public class JavaTest {
private int param;
private int param2;
private int result;

 @Parameters public static Collection data() {
return Arrays.asList(new Object[][]{ { 2, 4, 6 }, { 0, 0, 0 }, { -3, 9, 6 } });
}

 // 構造函數,對變量進行初始化
public JavaTest(int param, int param2, int result) {
this.param = param;
this.param2 = param2;
this.result = result;
}

@Test public void run() {
//do some thing use args, and assert it
int expected = param + param2;
assertEquals(expected, result);
}
} 

 

http://www.cnblogs.com/Natural-way/p/5204407.html
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM