JUnit Annotation

来源:互联网 发布:语音阅读文字软件 编辑:程序博客网 时间:2024/05/20 01:12

前段时间,junit annotation让我无言了一回,白疼了他两年,郁闷

junit 现在已经开发到了4.8.1版本,在这个版本中,共有19个annotation。最常用到的也有十来个。下面是无言之后写的一个junit 程序。没做什么功能,细心看,或是自己写一遍,或许那天,你就会用得上。

package com.junit.annotation;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assume.assumeThat;;

@RunWith(Theories.class)
public class AnnotationTest {

 @Rule
 public TestName testname = new TestName();
 
 @DataPoint
 public static String dPoint = "I love JUnit!";
 
 //测试@BeforeClass批注,在整个测试类中只运行一次,有别于@Before。
 //test the @BeforeClass annotation
 @BeforeClass
 public static void testBeforeClass() {
  System.out.println("BeforeClass");
 }
 
 //测试@Before批注,在每个测试方法运行前执行该方法。
 //test the @Before annotation
 @Before
 public void testBefore() {
  System.out.println("Before");
 }
 
 //测试@Test批注。
 //test the @Test annotation
 @Test
 public void testMethod() {
  Assert.assertEquals("testMethod",testname.getMethodName());
  System.out.println("testMethod");
 }
 
 //测试@Theory批注。
 //test the @Theory annotation
 @Theory
 public void testDataPoint(String interests) {
  //interests必须是I lvoe JUnit!,否则跳过该测试函数。
  //interests must be I lvoe JUnit!, or skip the test function.
  assumeThat(interests, is("I love JUnit!"));
  Assert.assertEquals("testDataPoint",testname.getMethodName());
  System.out.println("testDataPoint"+"/n"+dPoint);
 }
 
 //测试@Ignore批注
 //test the @Ignore annotation
 @Ignore
 @Test
 public void testIgnore() {
  Assert.assertEquals("testIgnore",testname.getMethodName());
  System.out.println("testIgnore");
 }
 
 //测试@After批注,每个test方法执行完成后运行此方法
 //test the @After annotation
 @After
 public void testAfter() {
  System.out.println("After");
 }
 
 //测试@AfterClass批注,在整个测试类中只运行一次,有别于@After
 //test the @AfterClass annotation
 @AfterClass
 public static void testAfterClass() {
  System.out.println("AfterClass");
 }
}
执行完,测试通过,从下图可以知道@Ignore的作用吧

  

再看下控制台中输出的信息

从上图可以得知,标的@BeforeClass和@AfterClass的测试方法只执行了一次,而@Before和@After在每个标有@Test方法执行前后都会执行一次。这也是这几个annotation的区别。

而@Rule这个annotation这里只说了一种用法,还有其它七种用法。

附上项目结构图

这段时间在看一本测试驱动开发的书,是极限编程创始人Kent Beck写的,非常不错。让测试程序运行起来,之后再消除那些重复设计,最终使代码整洁可用(clean code that works)。呵呵,还没看完,没悟到什么。纯属瞎扯蛋!

 

 

http://www.ltesting.net/html/55/182755-169117.html

原创粉丝点击