Java教程

java中写单元测试

本文主要是介绍java中写单元测试,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1. 引入pom

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <!-- <version>2.1.6.RELEASE</version>-->
</dependency>

 

2.  简单的测试方法类 

import org.junit.jupiter.api.Test;

public class DemoTest {

    @Test
    public void test() {
        System.out.println("true = " + true);
    }
}

 

3. springboot web项目中的单元测试

在src/test/java 下新建一个测试类,这样就可以测试项目里的各个方法了。运行测试类可能会稍微有点慢,因为他需要启动项目,运行完测试类后再关闭他。

import com.alibaba.fastjson.JSONObject;
import com.pingan.MybatisDemo01;
import com.pingan.domain.Parent;
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.SpringRunner;

import java.util.HashMap;

/**
 * 测试用例
 * FastJSON 的用法
 */

// 如果测试类在启动类的同级目录或者子目录下可以省略指定启动类
@SpringBootTest(classes = MybatisDemo01.class)
@RunWith(SpringRunner.class)
public class ParentControllerTest {

    @Autowired
    private ParentController parentController;

    @Test
    public void selectOne() {
        Parent parent = parentController.selectOne(1);
        // 将对你转成json
        String s = JSONObject.toJSONString(parent);
        System.out.println("parent = " + s);
        // 将json转成对象
        Parent parent1 = JSONObject.parseObject(s, Parent.class);
        System.out.println(parent1.getName());

        // json 转jsonObject
        JSONObject jsonObject = JSONObject.parseObject(s);
        String name = jsonObject.getString("name");
        System.out.println("name = " + name);

        // json 转map

        HashMap<String,String> hashMap = JSONObject.parseObject(s, HashMap.class);
        String relation = hashMap.get("relation");
        System.out.println("relation = " + relation);
    }
 
    @Test
    public void test01() {
        System.out.println("aaaaa");
    }

}

 

这篇关于java中写单元测试的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!