Java@Test注解实践 | 您所在的位置:网站首页 › java中test注解需要引用哪个jar包 › Java@Test注解实践 |
Java@Test注解实践
利用Junit测试的@Test注解,可以避免经常编写测试类。 @Test注解,方便我们对一段代码进行测试。 需要导入相应的包: import org.junit.Test;在方法前加上 @Test , 则该方法即为测试方法,可以执行。 下图为第五版《Java编程思想》的描述 但在实际使用中发现方法权限只能是public,不能用static修饰,而且不能用于内部类的方法。、 Case1 下面的代码可以正常执行,输出正常 import org.junit.Test; public class TestExample { private int num = 90; @Test public void testShow(){ System.out.println(num); } }下面的几种情况均不能执行。 Case2、3 用于内部类不能执行测试,添加“static”不能执行。 import org.junit.Test; public class TestExample { private int num = 90; class inter{ @Test public void testShow(){ System.out.println(num); } } } ------------------------------------------ import org.junit.Test; public class TestExample { private int num = 90; class inter{ @Test public static void testShow(){ System.out.println(num); } } }@Test注解源码描述。Junit首先构造类的一个新实例,然后调用带注释的方法。推测创建内部类对象和静态方法均不满足条件,后续补充相关知识后再进行完善。 一个测试类 AnnotationsTest.java import static org.junit.Assert.*; import java.util.*; import org.junit.*; public class AnnotationsTest { private ArrayList testList; @BeforeClass public static void onceExecutedBeforeAll() { System.out.println("@BeforeClass: onceExecutedBeforeAll"); } @Before public void executedBeforeEach() { testList = new ArrayList(); System.out.println("@Before: executedBeforeEach"); } @AfterClass public static void onceExecutedAfterAll() { System.out.println("@AfterClass: onceExecutedAfterAll"); } @After public void executedAfterEach() { testList.clear(); System.out.println("@After: executedAfterEach"); } @Test public void EmptyCollection() { assertTrue(testList.isEmpty()); System.out.println("@Test: EmptyArrayList"); } @Test public void OneItemCollection() { testList.add("oneItem"); assertEquals(1, testList.size()); System.out.println("@Test: OneItemArrayList"); } @Ignore public void executionIgnored() { System.out.println("@Ignore: This execution is ignored"); } }如果我们运行上面的测试,控制台输出将是以下几点: @BeforeClass: onceExecutedBeforeAll @Before: executedBeforeEach @Test: EmptyArrayList @After: executedAfterEach @Before: executedBeforeEach @Test: OneItemArrayList @After: executedAfterEach @AfterClass: onceExecutedAfterAll |
CopyRight 2018-2019 实验室设备网 版权所有 |