今天介绍一下Junit 中注解的使用。Junit中的注解有很多,这里不一一介绍。常用的注解如下:

  1. @Test: 测试方法

  2. @Ignore: 被忽略的测试方法

  3. @Before: 每一个测试方法之前运行

  4. @After: 每一个测试方法之后运行

  5. @BeforeClass: 所有测试开始之前运行

  6. @AfterClass: 所有测试结束之后运行


以下是示例代码:

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


}

上述代码的运行结果如下:

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

大家可以参考上面的代码和运行结果理解其中的意思。