这篇文章主要介绍了Java如何使用junit框架进行代码测试的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Java如何使用junit框架进行代码测试文章都会有所收获,下面我们一起来看看吧。
我写了一个时间工具类 DateTimeUtil, 里边有一个格式化为字符串的方法
现在我写了一个main函数来测试这个方法
package com.example;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeUtil {
/**
* 时间对象格式化为字符串
*
* @param date
* @return
*/
public static String toDateString(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.format(date);
}
public static void main(String[] args) {
Date now = new Date();
String nowString = DateTimeUtil.toDateString(now);
System.out.println(nowString);
}
}
如果,我在这个工具类中多增加几个方法,那么main方法的代码就需要来回改动
这时候可以借助IDE和测试类来实现多个方法的测试
使用junit
依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
maven 项目结构
$ tree
.
├── pom.xml
└── src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── DateTimeUtil.java
│ └── resources
└── test
├── java
│ └── com
│ └── example
│ └── DateTimeUtilTest.java
└── resources
DateTimeUtil.java
package com.example;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeUtil {
/**
* 时间对象格式化为字符串
*
* @param date
* @return
*/
public static String toDateString(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.format(date);
}
}
DateTimeUtilTest.java
package com.example;
import org.junit.Test;
import java.util.Date;
public class DateTimeUtilTest {
@Test
public void toDateString() {
Date now = new Date();
String nowString = DateTimeUtil.toDateString(now);
System.out.println(nowString);
}
}
注意:测试类的命名规则:xxxTest.java
这样依赖,代码看起来就干净整洁了
使用命令行运行测试
$ mvn test
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.example.DateTimeUtilTest
2023-02-16
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.059 secResults :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
关于“Java如何使用junit框架进行代码测试”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Java如何使用junit框架进行代码测试”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。