当前位置:网站首页>[learn junit5 from official documents] [II] [writingtests] [learning notes]
[learn junit5 from official documents] [II] [writingtests] [learning notes]
2022-04-23 02:51:00 【Hua Weiyun】
The following example provides JUnit Jupiter Minimum requirements for writing tests in .
package com.example.util;public class Calculator { public int add(int number1, int number2) { return number1 + number2; }}
package com.example;import com.example.util.Calculator;import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;public class MyFirstJUnitJupiterTests { private final Calculator calculator = new Calculator(); @Test void addition() { assertEquals(2, calculator.add(1, 1)); }}
1. Annotation Overview
JUnit Jupiter Support the following annotations for configuring the testing and extension framework . Unless otherwise stated , All core annotations are located in org.junit.jupiter.api In bag , This bag is in junit-jupiter-api Module .
| annotation | describe |
|---|---|
| @Test | Indicates that this method is a test method . differ JUnit4 Annotations , This annotation does not declare any properties , because JUnit Jupiter The test extension in runs based on its own special annotations . Unless it's covered , Otherwise, such methods will be inherited . |
| @ParameterizedTest | It shows that this method is a parametric test . Unless it's covered , Otherwise, such methods will be inherited . |
| @RepeatedTest | The representation method is the test template of repeated test . Unless it's covered , Otherwise, such methods will be inherited . |
| @TestFactory | The representation method is the test factory of dynamic test . Unless it's covered , Otherwise, such methods will be inherited . |
| @TestTemplate | The presentation method is the template of the test case , These test cases are designed to make multiple calls based on the data of the call context returned by the registered provider . |
| @TestClassOrder | Used in annotated test classes @Nested Test class configuration test class execution order . This class annotation will be inherited |
| @TestMethodOrder | Used to configure the test method execution sequence of annotated test classes ; Be similar to JUnit4 Of @FixMethodOrder. Such annotations will be inherited |
| @TestInstance | Used to configure the test instance life cycle for annotated test classes . This class annotation will be inherited . |
| @DisplayName | Declare the custom display name of the test class or test method . Such annotations do not inherit . |
| @DisplayNameGeneration | Declare a custom display name generator for the test class . Such annotations will be inherited . |
| @BeforeEach | The method representing the annotation should be in each part of the current class @Test、@RepeatedTest、@ParameterizedTest or @TestFactory Method is executed before ; similar JUnit4 Of @Before. Unless it's covered , Otherwise, such methods will be inherited . |
| @AfterEach | The method representing the annotation should be in each part of the current class @Test、@RepeatedTest、@ParameterizedTest or @TestFactory Method after execution ; similar JUnit4 Of @After. Unless it's covered , Otherwise, such methods will be inherited . |
| @BeforeAll | The method representing the annotation should be in all of the current class @Test、@RepeatedTest、@ParameterizedTest and @TestFactory Method is executed before ; Be similar to JUnit4 Of @BeforeClass. Such methods are inherited ( Unless they are hidden or covered ), And it must be static ( Unless used " Every kind per-class" Test instance lifecycle ) |
| @AfterAll | The method representing the annotation should be in all of the current class @Test、@RepeatedTest、@ParameterizedTest and @TestFactory Method after execution ; Be similar to JUnit4 Of @AfterClass. Such methods are inherited ( Unless they are hidden or covered ), And it must be static ( Unless used " Every kind per-class" Test instance lifecycle ) |
| @Nested | Indicates that the annotated class is a non static nested test class . Unless used " Every kind per-class" Test instance lifecycle , Otherwise, you can't directly in @Nested Test class @BeforehandAll and @AfterAll Method . Such annotations do not inherit . |
| @Tag | Used to declare tags for filtering tests at the class or method level ; Be similar to TestNG Test group or in JUnit4 Medium Category. Such annotations inherit at the class level , But not at the method level . |
| @Disabled | Used to disable test classes or test methods ; Be similar to JUnit4 Of @Ignore. Such annotations do not inherit . |
| @Timeout | Used to test 、 Test factory 、 Failure of a test template or lifecycle method when its execution exceeds a given duration . Such annotations will be inherited . |
| @ExtendWith | Used to register extensions declaratively . Such annotations will be inherited . |
| @RegisterExtension | Used to programmatically register extensions through fields . Unless these fields are hidden , Otherwise, these fields will be inherited . |
| @TempDir | It is used to provide temporary directory through field injection or parameter injection in life cycle method or test method ; be located org.junit.jupiter.api.io In bag . |
2. Meta annotation and composite annotation
JUnit Jupiter Annotations can be used as meta annotations . It means that you can define your own combination annotation , The annotation will automatically inherit the semantics of its meta annotation .
such as , You can create a named @Tag(“fast”) Custom combination annotation , Instead of copying and pasting from the entire code base @Tag(“fast”), As shown below . then @Fast Can be used as @Tag(“fast”) A direct alternative to .
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.junit.jupiter.api.Tag;@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Tag("fast")public @interface Fast {}
The following @Test The method describes @Fast Use of annotations
@Fast@Testvoid myFastTest(){ //...}
3. Test classes and methods
Test class : Any top-level class that contains at least one test method 、 Static member class or @Nested class . Test classes cannot be abstract , And must have a single constructor .
The test method : Use @Test、@RepeatedTest、@ParameerizedTest、@TestFactory or @TestTemplate Any instance method of direct annotation or meta annotation .
Life cycle approach : Use @BeforeAll、@AfterAll、@BeforeEach or @AfterEach Any method of direct annotation or meta annotation .
Test methods and lifecycle methods can be declared locally in the current test class , Inherit from superclass , You can also inherit from the interface ( Refer to test interfaces and default methods ). Besides , Test methods and life cycle methods should not be abstract , And must not return a value ( Return the required value @TestFactory Methods except ).
Visibility of classes and methods : Test class 、 Test methods and life cycle methods do not require public, But not for private. It is generally recommended to omit the test class 、 Of test methods and life cycle methods public Modifier , Unless there are technical reasons to do so . for example , When a test class is extended by a test class in another package . Classes and methods plus public Another technical reason is , In the use of Java Module system , Simplify testing on the module path .
The following test class demonstrates the use of @Test Methods and all supported lifecycle methods . More information on testing execution order and callback wrapping behavior .
Example : Set to fail the test
import org.junit.jupiter.api.*;import static org.junit.jupiter.api.Assertions.*;import static org.junit.jupiter.api.Assumptions.*;class StandardTests { @BeforeAll static void initAll() { } @BeforeEach void init() { } @Test void succeedingTest() { } @Test void failingTest() { fail("a failing test"); } @Test @Disabled("for demonstration purposes") void skippedTest(){ //not executed } @Test void abortedTest() { assumeTrue("abc".contains("Z")); fail("test should have been aborted"); } @AfterEach void tearDown() { } @AfterAll static void tearDownAll() { }}
Output results

Example : Set to pass the test
import org.junit.jupiter.api.*;import static org.junit.jupiter.api.Assertions.*;import static org.junit.jupiter.api.Assumptions.*;class StandardTests { @BeforeAll static void initAll() { } @BeforeEach void init() { } @Test void succeedingTest() { } @Test void failingTest() { //fail("a failing test"); } @Test @Disabled("for demonstration purposes") void skippedTest(){ //not executed } @Test void abortedTest() { assumeTrue("abc".contains("c")); //fail("test should have been aborted"); } @AfterEach void tearDown() { } @AfterAll static void tearDownAll() { }}
Output results

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220737087024.html
边栏推荐
- Devil cold rice 𞓜 078 devil answers the market in Shanghai and Nanjing; Communication and guidance; Winning the country and killing and screening; The purpose of making money; Change other people's op
- Jz76 delete duplicate nodes in linked list
- Modification du contenu de la recherche dans la boîte déroulante par PHP + MySQL
- 魔王冷饭||#078 魔王答上海、南京行情;沟通指导;得国和打杀筛选;赚钱的目的;改变别人看法
- Mosaic Routing: implement / home / news
- Looking for a job, writing a resume to an interview, this set of information is enough!
- Leetcode cooking
- Rhcsa day 4 operation
- Store consumption SMS notification template
- windows MySQL8 zip安装
猜你喜欢

Servlet template engine usage example

How to build an integrated industrial Internet plus hazardous safety production management platform?

Fashion MNIST dataset classification training

Flink stream processing engine system learning (I)

leangoo脑图-共享式多人协作思维导图工具分享

Shell script learning notes - regular expressions

C语言 171. 最近回文数
![[hcip] detailed explanation of six LSAS commonly used by OSPF](/img/31/3b92d42d16a056bf9db9e24471cefd.jpg)
[hcip] detailed explanation of six LSAS commonly used by OSPF

定了,今日起,本号粉丝可免费参与网易数据分析培训营!

C language 171 Number of recent palindromes
随机推荐
If MySQL / SQL server judges that the table or temporary table exists, it will be deleted
LeetCode 1450 - 1453
JZ35 replication of complex linked list
Machine learning (Zhou Zhihua) Chapter 14 probability graph model
First day of rhcsa
leangoo脑图-共享式多人协作思维导图工具分享
Servlet template engine usage example
Jupyter for local and remote access to ECS
国产轻量级看板式Scrum敏捷项目管理工具
Yes, from today on, our fans can participate in Netease data analysis training camp for free!
Slave should be able to synchronize with the master in tests/integration/replication-psync.tcl
Rhcsa second day operation
The penultimate K nodes in jz22 linked list
leetcode 烹饪料理
Windows MySQL 8 zip installation
Six very 6 computer driver managers: what software is good for driver upgrade? Recommended by the best computer driver management software abroad
字符串去掉空格问题
B blocks of the 46th ICPC Asian regional competition (Kunming)
MySQL insert free column
《信息系统项目管理师总结》第六章 项目人力资源管理