前言
- 因为上课的时候演示了JUnit单元测试,所以就顺便写一下这个玩意,测试方法啥的可以买书看。
- 本篇文章基于Web框架Springboot进行演示,其实随便一个maven项目就能实现。
JUnit
介绍
- JUnit是软件开发人员在进行模块开发时经常用到的测试工具,能在某种程度上体现自己开发的功能完善程度,在我眼中,单元测试是完善一个功能的细节,例如非法输入等小但容易忽视的地方。
- 它是一个回归测试的框架,但很多时候它的界限分的不是很清楚,既用于单元测试也用于白盒测试。
优点
- 在进行重构和写代码时,改一些测一些或写一些测一些,因为这两种都是增量式的,所以这样不仅能完善开发思维和逻辑,也能减少后续的回归测试的成本,避免消耗太多资源。
安装
- 直接在工程的pom.xml文件里引入依赖,具体的版本可以自己添加,也可以去maven仓库里下载对应的包。
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
简单使用JUnit
- 项目目录
- 测试文件都放在test文件夹下,我们要生成Cal类的对应测试类。
- Cal类的代码,springboot的注解以后我会出springboot的文章的,到时候再说。
import org.springframework.stereotype.Component;
/**
* @Author: 胡奇夫
* @QQ: 1579328766
* @CreateTime: 2020-10-13-21-44
* @Descirption:
*/
@Component
public class Cal {
public int add(int x,int y){
return x+y;
}
public double div(int x,int y){
return x/y;
}
public int sub(int x,int y){
return x-y;
}
public double mul(double x,double y){
return x*y;
}
}
- 生成CalTest操作:将光标移动到代码的类名Cal上,使用快捷键Alt+Enter,选择create test,下面是跳出来的弹窗,可以选择你要使用的测试版本,我用的是JUnit4,已经有JUnit5了,随意。下面可以选择生成的测试方法,我全选了,generator里的两个选项下面会说。
- 生成对应测试类的位置:
- 测试类的代码:
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
/**
* @Author: 胡奇夫
* @QQ: 1579328766
* @CreateTime: 2020-11-15-18-25
* @Descirption:
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class CalTest {
@Autowired
Cal cal;
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void add() {
//TestCase其实和Assert类差不多,我习惯用这个,直接用Assert也可以。
TestCase.assertEquals(5,cal.add(2,3));
//Assert
Assert.assertEquals(5,cal.add(2,3));
}
@Test
public void div() {
}
@Test
public void sub() {
}
@Test
public void mul() {
}
}
- @RunWith()里面的是使用的JUnit版本的启动类,也可以替换成SpringRunner.class。
- @Before就是在正式的Test(@Test)之前要做的事,例如提前服务器响应等操作。
- 在程序运行的时候,其实都是分组进行的,一个@Before、一个@Test和一个@After。
套件测试(打包测试)
- 一般完成一个模块后应该进行整体测试,这是必需的,这个时候使用Suite套件测试。
- 项目目录:AllTest类
- 代码:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* @Author: 胡奇夫
* @QQ: 1579328766
* @CreateTime: 2020-11-15-18-41
* @Descirption: 套件测试
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({})//花括号里添加需要测试的类
public class AllTest {
}
总结
- 项目中其实还用MockMvc等更多的测试注解,具体怎么测试也要根据模块的功能来选。
- 良好的单元测试能减少后续的回归测试的很多时间,所以JUnit的使用对于Java开发的后台是必不可少的,当然现在很多公司都在用go重构,要是大一的同学不妨直接学go吧!