java之单元测试
1、JUnit介绍
JUnit是一个Java的单元测试框架,平常学习Java时都是通过main函数来测试代码的,但是main()函数只能有一个,并且不能实现代码与测试分离。而单元测试可以进行代码与测试的分离,很好的组织测试代码。
2、通过Maven引入JUnit
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
编写一个业务类
public class serviceTest {
private String code;
serviceTest(String code){
this.code=code;
}
public String getCode(){
return this.code;
}
}
Maven项目专门有一个test模块,我们在这里建立一个测试类
这里的测试类命和方法名是自己取的,在测试方法上使用@test注解表明这是一个测试方法
还有其他常见注解
@Before:在测试方法执行前执行,一般用于初始化方法
@After: 在测试方法执行后执行,一般用于释放资源
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestJunit {
serviceTest serviceTest;
String code ;
@Test
public void testService(){
System.out.println(code);
}
//一般用于初始化
@Before
public void test1(){
System.out.println("运行前调用");
serviceTest=new serviceTest("hello world");
code = serviceTest.getCode();
}
//一般用于释放资源
@After
public void test2(){
System.out.println("运行后调用"+code);
}
}
运行结果:
运行前调用
hello world
运行后调用hello world
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)