junit及斷言


1、junit

 

junit要注意的細節:
1. 如果使用junit測試一個方法的時候,在junit窗口上顯示綠條那么代表測試正確,
 如果是出現了紅條,則代表該方法測試出現了異常不通過。
2. 如果點擊方法名、 類名、包名、 工程名運行junit分別測試的是對應的方法,類、 包中 的所有類的test方法,工程中的所有test方法。
3. @Test測試的方法不能是static修飾與不能帶有形參。
4. 如果測試一個方法的時候需要准備測試的環境或者是清理測試的環境,那么可以@Before、 @After 、@BeforeClass、 @AfterClass這四個注解。
@Before、 @After 是在每個測試方法測試的時候都會調用一次, @BeforeClass、 @AfterClass是在所有的測試方法測試之前與測試之后調用一次而已。

junit使用規范:
1. 一個類如果需要測試,那么該類就應該對應着一個測試類,測試類的命名規范 : 被測試類的類名+ Test.
2. 一個被測試的方法一般對應着一個測試的方法,測試的方法的命名規范是: test+ 被測試的方法的方法名

 

但是一般來說為了簡化測試,會直接在源程序上直接進行測試,但是測完之后必須刪除,以免影響測試效果

1.1對方法測試形式

        @Test //注解
	public	 void getMax(){
	        int a = 3;
		int b = 5 ;
		int max = a>b?a:b;
		System.out.println("最大值:"+max);
	}    

  當測試的方法是靜態或有參數的時候可以這樣解決:

 在書寫一個測試方法進行測試

	public  static void getMax(int a, int b){
		int max = a>b?a:b;
		System.out.println("最大值:"+max);
	}
      @Test  
     public void test1()
	{
		 getMax(1,2);
	}

 1.2對於測試事先准備環境的解決 

比如在測試對文件的操作的方法的時候,要有文件的創建等等,之后可能還有刪除操作

 使用:@Before、 @After 、@BeforeClass、 @AfterClass

@Before、 @After 是在每個測試方法測試的時候都會調用一次, @BeforeClass、 @AfterClass是在所有的測試方法測試之前與測試之后調用一次而已。

而且@BeforeClass、 @AfterClass注釋的方法必須是靜態的方法

public class Demo2 {
	
	//准備測試的環境
	//@Before
	@BeforeClass
	public static void beforeRead(){
		System.out.println("准備測試環境成功...");
	}
	
	
	//讀取文件數據,把把文件數據都
	@Test
	public void readFile() throws IOException{
		FileInputStream fileInputStream = new FileInputStream("F:\\a.txt");
		int content  = fileInputStream.read();
		System.out.println("內容:"+content);
	}
	
	
	@Test
	public void sort(){
		System.out.println("讀取文件數據排序..");
	}

	
	//清理測試環境的方法
//	@After 
	@AfterClass
	public static void afterRead(){
		System.out.println("清理測試環境..");
	}
	

}

  

2、斷言

進行預先判斷,不用再從控制台看輸出

Assert.assertSame(expected,actual);
Assert.assertSame(5, max); // expected 期望   actual  真實    底層是用==進行比較
Assert.assertSame(new String("abc"), "abc");
Assert.assertEquals(new String("abc"), "abc"); //底層是使用Equals方法比較的
Assert.assertNull("aa");
Assert.assertTrue(true);
import org.junit.Test;

//測試類
public class ToolTest {
    
    @Test
    public void testGetMax(){
        int max = Tool.getMax();
        if(max!=5){
            throw new RuntimeException();
        }else{
            System.out.println("最大值:"+ max);
        }
        
        //斷言
        //Assert.assertSame(5, max); // expected 期望   actual  真實     ==
//        Assert.assertSame(new String("abc"), "abc");
//        Assert.assertEquals(new String("abc"), "abc"); //底層是使用Equals方法比較的
//        Assert.assertNull("aa");
//        Assert.assertTrue(true);
    
    }
    
    @Test
    public void  testGetMin(){
        int min = Tool.getMin(); 
        if(min!=3){
            throw new RuntimeException();
        }else{
            System.out.println("最小值:"+ min);
        }
    }
    
    

}

 


免責聲明!

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



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