欢迎光临
我们一直在努力

Java如何使用junit框架进行代码测试

这篇文章主要介绍了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 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

关于“Java如何使用junit框架进行代码测试”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Java如何使用junit框架进行代码测试”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注云搜网行业资讯频道。

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。