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);
        }
    }
    
    

}

 

posted @ 2017-02-23 11:28  mslog  阅读(2064)  评论(0编辑  收藏  举报