静态方法的单元测试Mockito
直接上例子
方法

public ArrayList<SearchFields> convertToSearchFieldsList(HashMap<String, ArrayList<SearchFieldValue>> filter) {
        return ESUtils.convertToSearchFieldsList(filter);
    }

convertToSearchFieldsList方法就是静态方法,可看下:

在这里插入图片描述

单测

import org.junit.Assert;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;

@Test
    public void testConvertToSearchFieldsList() {
        SearchFields searchFields = new SearchFields();
        searchFields.setOperation("2");
        ArrayList<SearchFields> combineRule = new ArrayList<>();
        combineRule.add(searchFields);
        HashMap<String, ArrayList<SearchFieldValue>> filter = new HashMap<>();
        ArrayList<SearchFieldValue> list = new ArrayList<>();
        SearchFieldValue searchFieldValue = new SearchFieldValue();
        searchFieldValue.setVal("er");
        list.add(searchFieldValue);
        filter.put("1",list);
        try(MockedStatic<ESUtils> theMock = Mockito.mockStatic(ESUtils.class)) {
            theMock.when(() -> ESUtils.convertToSearchFieldsList(Mockito.any())).thenReturn(combineRule);
        }
        Assertions.assertThat(ucompanyServiceImpl.convertToSearchFieldsList(filter));
    }

【加粗提示】

try(MockedStatic<ESUtils> theMock = Mockito.mockStatic(ESUtils.class)) {
            theMock.when(() -> ESUtils.convertToSearchFieldsList(Mockito.any())).thenReturn(combineRule);
        }

更多推荐