当前位置:网站首页>[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
边栏推荐
- Practice of industrial defect detection project (III) -- Based on FPN_ PCB defect detection of tensorflow
- Shell script learning notes - regular expressions
- Slave should be able to synchronize with the master in tests/integration/replication-psync.tcl
- First knowledge of C language ~ branch statements
- [wechat applet] set the bottom menu (tabbar) for the applet
- Classification and regression tree of machine learning
- Leangoo brain map - shared multi person collaborative mind mapping tool
- [hcip] detailed explanation of six LSAS commonly used by OSPF
- Error installing Mongo service 'mongodb server' on win10 failed to start
- 工业互联网+危化安全生产综合管理平台怎样建
猜你喜欢
基于Scrum进行创新和管理
windows MySQL8 zip安装
Modification du contenu de la recherche dans la boîte déroulante par PHP + MySQL
JVM runtime data area (I)
Hack the box optimum
First knowledge of C language ~ branch statements
Day 3 of learning rhcsa
解决win7 中powershell挖矿占用CPU100%
Linux Redis ——Redis HA Sentinel 集群搭建详解 & Redis主从部署
Android high-level interview must ask: overall business and project architecture design and reconstruction
随机推荐
The penultimate K nodes in jz22 linked list
Day 4 of learning rhcsa
5W of knowledge points
Fashion MNIST dataset classification training
Flink learning (XI) watermark
Linux redis - redis database caching service
Essential qualities of advanced programmers
MySQL复杂查询使用临时表/with as(类似表变量)
Jupyter for local and remote access to ECS
Decision tree principle of machine learning
Using go language to build web server
Looking for a job, writing a resume to an interview, this set of information is enough!
Rhcsa day 3 operation
If MySQL / SQL server judges that the table or temporary table exists, it will be deleted
Use of go language web Middleware
Table space capacity query and expansion of Oracle Database
【Hcip】OSPF常用的6种LSA详解
Huashu "deep learning" and code implementation: 01 Linear Algebra: basic concepts + code implementation basic operations
机器学习(周志华) 第十四章概率图模型
Modification du contenu de la recherche dans la boîte déroulante par PHP + MySQL