当前位置:网站首页>Optimization of unit test efficiency: why test programs? What are the benefits of testing?
Optimization of unit test efficiency: why test programs? What are the benefits of testing?
2022-06-30 13:37:00 【Software testing Fairy】
unit testing (Unit Testing) Also known as module testing , It's for program modules ( The smallest unit of software design ) To test the correctness . A program unit is the smallest testable part of an application . Simply speaking , It is to test whether the stability of the data meets the expectations of the program . When it comes to testing , Why should we test the program ? What benefits does testing bring to the program ?

We may inadvertently make mistakes in our daily development , If you wait until the final stage to test the project results , Found a mistake , It's hard for us to find it at this time Bug Where is the source of . We all know , It is possible that an error will lead to a step-by-step error .
The test is in our above statement , It's very important , When we finish a small module of the project , First, test whether the small module is correct or meets the expectations , If it is wrong or does not meet expectations, it needs to be revised repeatedly , Until correct or expected , That is, unit tests are used .
The coding specification of unit test generally involves the following contents :
Class name : Define test classes , The class name is determined by the name of the tested class Test constitute . for example :CalculatorTest;
Package name : The defined test class needs to be placed in xxx.xxx.xxx.test In bag . for example :package com.autodrive.test;
Method name : The method name of a test method can be defined in two ways test Test methods and test methods . for example :testCheck and check;
Return value : Because our method is only tested in class , Can run independently , So you don't need to process any return values , So here we use void. for example :public void check();
parameter list : Because our method is used to test , As for the input of parameter list, it is not necessary . When testing, we can pass in the required parameters by ourselves . So this parameter list is empty . for example : for example :public void check();
@Test annotation : Tests need to be run to complete . If we only have one main Method , Obviously, we still need to comment out the tested structures . To solve this problem, we need to add... Above the test method @Test Annotation to complete the test , As long as it is the method of adding the annotation , You can run this method alone to complete the test .
IDEA Quick import Junit4、5: Use IDEA Little buddy , Here comes your gospel . We can create test classes and methods first , Then add... Above the test method @Test annotation , here IDEA According to the @Test The annotation is red , That's when we use Alt + Enter Key combination to open the import Junit Unit test list , Then choose Junit4 perhaps Junit5 determine .
stay SpringBoot The following notes and descriptions are often used in unit tests :
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Transactional
@Rollback(true) // Automatic transaction rollback , The default is true. Don't write
public class NoticeServiceTest {
@Autowired
private NoticeService noticeService;
@Test
public void sayHello() {
helloService.sayHello("zhangsan");
}
}
In the example above ,@SpringBootTest Launched the SpringBoot Environmental Science , Scan the application for spring To configure , And build a complete Spring Context, Its classes = Application.class Started the whole project . adopt @SpringBootTest We can specify the startup class , Or to @SpringBootTest Parameters of webEnvironment The assignment is SpringBootTest.WebEnvironment.RANDOM_PORT, This will start web Containers , And listen to a random port , meanwhile , Automatically assemble one for us TestRestTemplate Type of bean To assist us in sending test requests .
@Transactional Indicates that the database is called and transacted ;@RunWith(SpringRunner.class) The statement in Spring Unit testing in the environment of , such Spring The relevant annotations will be recognized and take effect , and @Autowired Launched the Spring.
When the project uses @Component annotation , stay SpringBoot When the project starts, it will be instantiated / start-up , This @Component Annotated classes have multithreaded methods , As defined in the startup class ApplicationStartup Class started , So when you execute unit tests , Due to the impact of multithreaded tasks , It may cause data modification to your database , Even if you use the transaction rollback annotation .
Efficient unit tests should be separated from the database , To meet the requirements of quick start and complete the test 、 Support the requirements of inter service invocation . The above example can be optimized through the following points :
1. start-up Spring Will make run->Junit Test The program slows down , This is one of the reasons why running unit tests is slow every time . Then unit testing is to test only the methods of a certain class , start-up Spring Many times it is superfluous , So we only need the corresponding entity class instance . Inject... When needed bean When , We directly new.
private NoticeService noticeService = new NoticeService();
2. @SpringBootTest Is in SpringBoot Used on the project , It's in @SpringBootContextLoader On the basis of , Reading of configuration file attributes , Will read 、 Parse some project configuration files , Also connect to the database , Then if the startup class has another startup class 、@Component、 Multithreading etc. , Unit tests can often avoid starting SpringBoot, Reduce the amount of time it takes to start , I don't use @SpringBootTest annotation .
3. Assertions should be used to determine whether unit test results meet expectations .
4. @RunWith stay JUnit Many of them Runner, They are responsible for invoking specific test code , every last Runner Each has its own special functions , You have to choose different... According to your needs Runner To run your test code , And they usually use SpringRunner.class. If we simply do ordinary Java test , Don't involve Spring Web project , It can be omitted @RunWith annotation , In this way, the system will automatically use the default Runner To run your code .
5. Unit tests can pass Mock The data method avoids the call to the database , Reduce a lot of database connection time .Mock It is a step to simulate all operations on the database , Do not execute any SQL, If we directly simulate the code execution of this operation database, it will be successful , And it can simulate any return value , There are two main comments . As long as it's local , His writing bean, You can use @MockBean, It will simulate all the methods of operating the database . If it is a method without a return value , We can leave it alone . If it is a method with a return value , We can give it back the values we need to simulate . If it is our local , Call another company , Interfaces written for us elsewhere , Not to operate our own database , It is we who have written the reference , Others give us a return value , We will use @SpyBean.
Mock The necessary dependencies are as follows :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Through the above optimization , It can greatly shorten our single test time , Improve our development efficiency .
Last :
You can go to my personal number :atstudy-js, You can get one for free 10G Software Test Engineer interview classic documents . And the corresponding video learning tutorial is free to share ! It includes basic knowledge 、Linux necessary 、Mysql database 、 Caught tools 、 Interface testing tool 、 Test advanced -Python Programming 、Web automated testing 、APP automated testing 、 Interface automation testing 、 Testing advanced continuous integration 、 Test architecture development test framework 、 Performance test, etc .
These test data , For doing 【 software test 】 For our friends, it should be the most comprehensive and complete war preparation warehouse , This warehouse also accompanied me through the most difficult journey , I hope it can help you !
边栏推荐
猜你喜欢

一条查询SQL是如何执行的

Apache Doris Compaction優化百科全書

JS converts an array to a two-dimensional array based on the same value

提权扫描工具
![[deep anatomy of C language] storage principle of float variable in memory & comparison between pointer variable and](/img/3d/5d7fafba4ff7903afbd51d6d58dcdf.png)
[deep anatomy of C language] storage principle of float variable in memory & comparison between pointer variable and "zero value"

Postman génère automatiquement des fragments de code Curl

Goods and services - platform properties

Unity animator parameter

SQL考勤统计月报表

Introduction to two types of rxjs observable operators
随机推荐
RK356x U-Boot研究所(命令篇)3.2 help命令的用法
Postman génère automatiquement des fragments de code Curl
Kaniko official documents - build images in kubernetes
【刷题篇】供暖器
SQL编程问题,测试用例不通过
幸运哈希竞猜系统开发(源码部署)趣投哈希游戏玩法开发(案例需求)
Paper interpretation (AGC) attributed graph clustering via adaptive graph revolution
Read all the knowledge points about enterprise im in one article
All the abnormal knowledge you want is here
[Title brushing] coco, who likes bananas
Golang Basics - string and int, Int64 inter conversion
[recruitment (Guangzhou)] Chenggong Yi (Guangzhou) Net core middle and Senior Development Engineer
SQL考勤统计月报表
Motor control Clarke( α/β) Derivation of equal amplitude transformation
防火墙基础之总部双机热备与分支基础配置
我如何才能保护我的私钥?
Idea 2021.3 golang error: rning: undefined behavior version of delve is too old for go version 1.18
get请求与post提交区别的简易理解
Resource realization applet opening traffic main tutorial
数字时代,XDR(扩展检测与响应)的无限可能