【Springboot学习】在Springboot中使用Junit进行测试
前言
一般在测试Java用例时使用的都是main方法,这样就需要我们不断地修改main方法,导致测试代码通常无法保留或者不规范,因此Java提供了Junit进行更为优雅的白盒测试方式。
步骤
- 定义一个测试类(测试用例)
- 测试类名: 被测试类名+Test CalculatorTest
- 包名: xxx.xxx.xx.test com.tnxts.test
import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class testCalculate { }
- 定义测试方法: 可以独立运行
- 方法名: test测试的方法名 testAdd()
- 返回值: void
- 参数列表: 空参
import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class testCalculate { @Test public void testAdd(){ Calculate c = new Calculate(); int resultA = c.add(1,2); int resultB = c.sub(1,2); System.out.println(resultA); System.out.println(resultB); } }
- 使用断言判断正确与否
import org.junit.Assert; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class testCalculate { @Test public void testAdd(){ Calculate c = new Calculate(); int resultA = c.add(1,2); int resultB = c.sub(1,2); Assert.assertEquals(3,resultA); } }
- 结果(测试成功)
@Before与@After
- 使用@Before注解的方法在测试方法执行前执行,可以用作测试方法的初始化,如资源的申请
- 使用@Before注解的方法在测试方法执行后执行,可以用作资源的回收
测试
测试代码
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class testCalculate {
@Before
public void init()
{
System.out.println("before...");
}
@Test
public void test(){
System.out.println("test...");
}
@After
public void close()
{
System.out.println("After...");
}
}
测试结果
注意
即使test方法出现了异常,使用after和before仍然会正常执行。
本文作者:Texley
本文链接:https://www.cnblogs.com/texley/p/16439331.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律