單元測試—IDEA+Junit5+JSON

前言

單元測試是開發(fā)自驗必不可少的一環(huán),IDEA本身已經(jīng)默認集成單元測試的插件,不用再額外安裝插件,但是Junit5目前只支持CSV格式的參數(shù)注入,此處在前人JSON數(shù)據(jù)驅(qū)動的基礎上,支持json文件多參數(shù)注入。

因為我這邊的測試更偏向于多json文件參數(shù)組裝復用,所以JsonFileArgumentsProvider.java代碼略有變動。

Maven依賴

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-params</artifactId>
            <version>5.7.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>

路徑目錄

路徑目錄

此處的junitJson文件用于擴展Junit支持JSON格式的參數(shù)注入,直接下載后貼在各自的項目中就行,我這邊的單元測試不作提交,所以擴展的代碼也就放在test類了,其中resources目錄用來存放json文件

JsonFileArgumentsProvider.java支持多JSON文件組裝參數(shù)注入

package junitJson;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.support.AnnotationConsumer;
import org.junit.platform.commons.util.Preconditions;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.stream.Stream;

public class JsonFileArgumentsProvider implements ArgumentsProvider, AnnotationConsumer<JsonFileSource> {

    private final BiFunction<Class, String, InputStream> inputStreamProvider;

    private String[] resources;

    public JsonFileArgumentsProvider() throws Exception {
        this(Class::getResourceAsStream);
    }

    JsonFileArgumentsProvider(BiFunction<Class, String, InputStream> inputStreamProvider) {
        this.inputStreamProvider = inputStreamProvider;
    }

    private static Object values(InputStream inputStream) {
        Object jsonObject = null;
        try {
            jsonObject = JSONObject.parse(IOUtils.toString(inputStream, "utf8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    static Stream<Object> getObjectStream(Object jsonObject) {
        if (jsonObject instanceof JSONArray) {
            return ((JSONArray) jsonObject).stream();
        } else if (jsonObject instanceof JSONObject) {
            return Stream.of(jsonObject);
        }
        return null;
    }

    @Override
    public void accept(JsonFileSource jsonFileSource) {
        resources = jsonFileSource.resources();
    }

    @Override
    public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
        Object[] objects = Arrays.stream(resources)
            .map(resource -> openInputStream(context, resource))
            .map(JsonFileArgumentsProvider::values)
            .toArray();
        return Stream.of(Arguments.of(objects));
    }

    private InputStream openInputStream(ExtensionContext context, String resource) {
        Preconditions.notBlank(resource, "Classpath resource [" + resource + "] must not be null or blank");
        Class<?> testClass = context.getRequiredTestClass();
        return Preconditions.notNull(inputStreamProvider.apply(testClass, resource),
            () -> "Classpath resource [" + resource + "] does not exist");
    }
}

IDEA生成單元測試類

Alt + Insert

第一步

勾選生成

生成測試類demo

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CalculationEntry.class)
@DisplayName("IPCA場景覆蓋測試類")
class CalculationEntryTest {

    @Autowired
    private CalculationEntry calculationEntry;

    @DisplayName("A->B->C單鏈路全數(shù)據(jù)場景測試")
    @ParameterizedTest
    @JsonFileSource(resources = {"/singleResult.json", "/singleResultBack.json","/deviceMacList.json"})
    void singleLinkFullData(JSONArray ipcaNodeInfoList, JSONArray ipcaNodeInfoBackList, JSONArray deviceMacList) {
        System.out.println(ipcaNodeInfoList);
    }
}
  • Junit5使用@ExtendWith(SpringExtension.class)實現(xiàn)和spring的互動
  • @ContextConfiguration使用classes參數(shù)按需注入所用的類,避免直接路徑注入XML其他啟動類報錯

參考鏈接

  1. Junit 5官方文檔中文版

  2. Junit5加上json數(shù)據(jù)源

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。