今天介绍一下Junit 中注解的使用。Junit中的注解有不少,这里不一一介绍。经常使用的注解以下:java
@Test: 测试方法bash
@Ignore: 被忽略的测试方法ide
@Before: 每个测试方法以前运行测试
@After: 每个测试方法以后运行this
@BeforeClass: 全部测试开始以前运行spa
@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