Junit (三) 註解的使用

  今天介紹一下Junit 中註解的使用。Junit中的註解有不少,這裏不一一介紹。經常使用的註解以下:java

  1. @Test: 測試方法bash

  2. @Ignore: 被忽略的測試方法ide

  3. @Before: 每個測試方法以前運行測試

  4. @After: 每個測試方法以後運行this

  5. @BeforeClass: 全部測試開始以前運行spa

  6. @AfterClass: 全部測試結束以後運行rest


如下是示例代碼:ci

package com.junit.test;

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

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

import com.junit.junit4.T;

public class TTest {
	
	/**
	 * 全部測試以前運行
	 */
	@BeforeClass
	public static void  beforeClass(){
		System.out.println("This is a beforeClass method");
	}
	
	/**
	 * 全部測試以後運行
	 */
	@AfterClass
	public static void  afterClass(){
		System.out.println("This is a afterClass method");
	}
	
	/**
	 * 每個測試方法以前運行
	 */
	@Before
	public void before(){
		System.out.println("this is a before method");
	}
	
	/**
	 * 每個測試方法以後運行
	 */
	@After
	public void after(){
		System.out.println("this is a before method");
	}

	@Test
	public void testAdd() {
		//fail("Not yet implemented");
		int sum = new T().add(5, 3);
		
		//判斷程序運行結果是否與指望值一致
		assertEquals(8, sum);
	}
	
	@Test
	public void testAdd2() {
		//fail("Not yet implemented");
		int sum = new T().add(5, 3);
		
		//判斷程序運行結果是否與指望值一致
		assertEquals(8, sum);
		assertTrue("This is TestString",8>sum);
		//assertThat("assertThat",8 > sum);
	}
	
	@Test
	public void testMinus(){
		int result = new T().minus(8, 2);
		assertThat(result,is(4));
	}


}

上述代碼的運行結果以下:it

This is a beforeClass method
this is a before method
this is a before method
this is a before method
this is a before method
this is a before method
this is a before method
This is a afterClass method

你們能夠參考上面的代碼和運行結果理解其中的意思。class

相關文章
相關標籤/搜索