Java@Test注解实践 您所在的位置:网站首页 java中test注解需要引用哪个jar包 Java@Test注解实践

Java@Test注解实践

2024-01-01 06:48| 来源: 网络整理| 查看: 265

Java@Test注解实践

利用Junit测试的@Test注解,可以避免经常编写测试类。

@Test注解,方便我们对一段代码进行测试。 需要导入相应的包:

import org.junit.Test;

在方法前加上 @Test , 则该方法即为测试方法,可以执行。

下图为第五版《Java编程思想》的描述

image-20220219201522876

但在实际使用中发现方法权限只能是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首先构造类的一个新实例,然后调用带注释的方法。推测创建内部类对象和静态方法均不满足条件,后续补充相关知识后再进行完善。

image-20220219202244062

补充 注解 描述 @Test public void method() 测试注释指示该公共无效方法它所附着可以作为一个测试用例。 @Before public void method() Before注释表示,该方法必须在类中的每个测试之前执行,以便执行测试某些必要的先决条件。 @BeforeClass public static void method() BeforeClass注释指出这是附着在静态方法必须执行一次并在类的所有测试之前。发生这种情况时一般是测试计算共享配置方法(如连接到数据库)。 @After public void method() After 注释指示,该方法在执行每项测试后执行(如执行每一个测试后重置某些变量,删除临时变量等) @AfterClass public static void method() 当需要执行所有的测试在JUnit测试用例类后执行,AfterClass注解可以使用以清理建立方法,(从数据库如断开连接)。注意:附有此批注(类似于BeforeClass)的方法必须定义为静态。 @Ignore public static void method() 当想暂时禁用特定的测试执行可以使用忽略注释。每个被注解为@Ignore的方法将不被执行。

一个测试类

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 实验室设备网 版权所有