pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

模擬;使用列表調用驗證方法,忽略列表中元素的

Mockito; verify method was called with list, ignore order of elements in list(模擬;使用列表調用驗證方法,忽略列表中元素的順序)
本文介紹了模擬;使用列表調用驗證方法,忽略列表中元素的順序的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有一個類 (ClassA) 可以獲取目錄中的文件.它掃描給定目錄以查找匹配正則表達式的文件.對于每個匹配的文件,它會將一個文件對象添加到列表中.處理完目錄后,會將文件列表傳遞給另一個類(ClassB)進行處理

I have a class (ClassA) that get the files in a directory. It scans the given directory for files matching a regex. For each matching file, it adds a File Object to a list. Once the directory is processed, it passes the List of Files to another Class (ClassB) for processing

我正在為 ClassA 編寫單元測試,所以我正在使用 Mockito 模擬 ClassB,并將其注入 ClassA.然后我想在不同的場景中驗證傳遞給 ClassB 的列表的內容(即我的模擬)

I am writing unit tests for ClassA, so am mocking ClassB using Mockito, and injecting it into ClassA. I then want to verify in different scenarios the contents of the list that is passed to ClassB (ie my mock)

我已將代碼剝離為以下內容

I've stripped back the code to the following

public class ClassA implements Runnable {

    private final ClassB classB;

    public ClassA(final ClassB classB) {
        this.classB = classB;
    }

    public List<File> getFilesFromDirectories() {
        final List<File> newFileList = new ArrayList<File>();
        //        ...
        return newFileList;
    }

    public void run() {
        final List<File> fileList = getFilesFromDirectories();

        if (fileList.isEmpty()) {
            //Log Message
        } else {
            classB.sendEvent(fileList);
        }
    }
}

測試類是這樣的

    @RunWith(MockitoJUnitRunner.class)
    public class AppTest {

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Mock
    private ClassB mockClassB;

    private File testFileOne;

    private File testFileTwo;

    private File testFileThree;

    @Before
    public void setup() throws IOException {
        testFileOne = folder.newFile("testFileA.txt");
        testFileTwo = folder.newFile("testFileB.txt");
        testFileThree = folder.newFile("testFileC.txt");
    }

    @Test
    public void run_secondFileCollectorRun_shouldNotProcessSameFilesAgainBecauseofDotLastFile() throws Exception {
        final ClassA objUndertest = new ClassA(mockClassB);

        final List<File> expectedFileList = createSortedExpectedFileList(testFileOne, testFileTwo, testFileThree);
        objUndertest.run();

        verify(mockClassB).sendEvent(expectedFileList);
    }

    private List<File> createSortedExpectedFileList(final File... files) {
        final List<File> expectedFileList = new ArrayList<File>();
        for (final File file : files) {
            expectedFileList.add(file);
        }
        Collections.sort(expectedFileList);
        return expectedFileList;
    }
}

問題是這個測試在 Windows 上運行良好,但在 Linux 上失敗.原因是在windows上,ClassA列出文件的順序與expectedList相匹配,所以行

The problem is that this test works perfectly fine on windows, but fails on Linux. The reason being that on windows, the order that ClassA list the files matches the expectedList, so the line

verify(mockClassB).sendEvent(expectedFileList);

在 Windows 上會導致問題 expecetdFileList = {FileA, FileB, FileC},而在 Linux 上會是 {FileC, FileB, FileA},因此驗證失敗.

is causing the problem expecetdFileList = {FileA, FileB, FileC} on Windows, whereas on Linux it will be {FileC, FileB, FileA}, so the verify fails.

問題是,我如何在 Mockito 中解決這個問題.有沒有辦法說,我希望這個方法被這個參數(shù)調用,但是我不關心列表內容的順序.

The question is, how do I get around this in Mockito. Is there any way of saying, I expect this method to be be called with this parameter, but I don't care about the order of the contents of the list.

我確實有一個解決方案,我只是不喜歡它,我寧愿有一個更干凈、更易于閱讀的解決方案.

I do have a solution, I just don't like it, I would rather have a cleaner, easier to read solution.

我可以使用 ArgumentCaptor 獲取傳遞給模擬的實際值,然后對其進行排序,并將其與我的預期值進行比較.

I can use an ArgumentCaptor to get the actual value passed into the mock, then can sort it, and compare it to my expected values.

    final ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
    verify(mockClassB).method(argument.capture());
    Collections.sort(expected);
    final List<String> value = argument.getValue();
    Collections.sort(value);
    assertEquals(expecetdFileList, value);

推薦答案

在另一個答案中指出,如果您不關心訂單,您可能最好更改界面,使其不關心訂單.

As noted in another answer, if you don't care about the order, you might do best to change the interface so it doesn't care about the order.

如果順序在代碼中很重要,但在特定測試中不重要,您可以像以前一樣使用 ArgumentCaptor.代碼有點混亂.

If order matters in the code but not in a specific test, you can use the ArgumentCaptor as you did. It clutters the code a bit.

如果這是您可能在多個測試中執(zhí)行的操作,則最好使用適當?shù)?Mockito Matchers 或 Hamcrest Matchers,或者自己動手制作(如果你找不到滿足需要的).hamcrest matcher 可能是最好的,因為它可以在 mockito 之外的其他上下文中使用.

If this is something you might do in multiple tests, you might do better to use appropriate Mockito Matchers or Hamcrest Matchers, or roll your own (if you don't find one that fills the need). A hamcrest matcher might be best as it can be used in other contexts besides mockito.

對于本示例,您可以按如下方式創(chuàng)建 hamcrest 匹配器:

For this example you could create a hamcrest matcher as follows:

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyMatchers {
    public  static <T> Matcher<List<T>> sameAsSet(final List<T> expectedList) {
        return new BaseMatcher<List<T>>(){
            @Override
            public boolean matches(Object o) {
                List<T> actualList = Collections.EMPTY_LIST;
                try {
                    actualList = (List<T>) o;
                }
                catch (ClassCastException e) {
                    return false;
                }
                Set<T> expectedSet = new HashSet<T>(expectedList);
                Set<T> actualSet = new HashSet<T>(actualList);
                return actualSet.equals(expectedSet);
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("should contain all and only elements of ").appendValue(expectedList);
            }
        };
    }
}

然后驗證碼變成:

verify(mockClassB).sendEvent(argThat(MyMatchers.sameAsSet(expectedFileList)));

如果您改為創(chuàng)建模擬匹配器,則不需要 argThat,它基本上將 hamcrest 匹配器包裝在模擬匹配器中.

If you instead created a mockito matcher, you wouldn't need the argThat, which basically wraps a hamcrest matcher in a mockito matcher.

這會將排序或轉換的邏輯移出您的測試并使其可重用.

This moves the logic of sorting or converting to set out of your test and makes it reusable.

這篇關于模擬;使用列表調用驗證方法,忽略列表中元素的順序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯(lián)網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!

相關文檔推薦

How to mock super reference (on super class)?(如何模擬超級參考(在超級類上)?)
Java mock database connection(Java 模擬數(shù)據(jù)庫連接)
Mockito ClassCastException - A mock cannot be cast(Mockito ClassCastException - 無法投射模擬)
Set value to mocked object but get null(將值設置為模擬對象但獲取 null)
How to mock DriverManager.getConnection(...)?(如何模擬 DriverManager.getConnection(...)?)
Is it possible to create a mock object that implements multiple interfaces with EasyMock?(是否可以使用 EasyMock 創(chuàng)建一個實現(xiàn)多個接口的模擬對象?)
主站蜘蛛池模板: 设定时间记录电子秤-自动累计储存电子秤-昆山巨天仪器设备有限公司 | 航拍_专业的无人机航拍摄影门户社区网站_航拍网 | 北京百度网站优化|北京网站建设公司-百谷网络科技 | 污水处理设备,一体化泵站,一体化净水设备-「梦之洁环保设备厂家」 | 沧州友城管业有限公司-内外涂塑钢管-大口径螺旋钢管-涂塑螺旋管-保温钢管生产厂家 | 定制异形重型钢格栅板/钢格板_定做踏步板/排水沟盖板_钢格栅板批发厂家-河北圣墨金属制品有限公司 | 万博士范文网-您身边的范文参考网站Vanbs.com | 工业车间焊接-整体|集中除尘设备-激光|等离子切割机配套除尘-粉尘烟尘净化治理厂家-山东美蓝环保科技有限公司 | 高速龙门架厂家_监控杆_多功能灯杆_信号灯杆_锂电池太阳能路灯-鑫世源照明 | 净水器代理,净水器招商,净水器加盟-FineSky德国法兹全屋净水 | 上海恒驭仪器有限公司-实验室平板硫化机-小型平板硫化机-全自动平板硫化机 | 猎头招聘_深圳猎头公司_知名猎头公司 | 智能门锁电机_智能门锁离合器_智能门锁电机厂家-温州劲力智能科技有限公司 | 恒温恒湿试验箱厂家-高低温试验箱维修价格_东莞环仪仪器_东莞环仪仪器 | 老房子翻新装修,旧房墙面翻新,房屋防水补漏,厨房卫生间改造,室内装潢装修公司 - 一修房屋快修官网 | 电子元器件呆滞料_元器件临期库存清仓尾料_尾料优选现货采购处理交易商城 | 焊缝跟踪系统_激光位移传感器_激光焊缝跟踪传感器-创想智控 | HYDAC过滤器,HYDAC滤芯,现货ATOS油泵,ATOS比例阀-东莞市广联自动化科技有限公司 | 知网论文检测系统入口_论文查重免费查重_中国知网论文查询_学术不端检测系统 | 药品仓库用除湿机-变电站用防爆空调-油漆房用防爆空调-杭州特奥环保科技有限公司 | 色谱柱-淋洗液罐-巴罗克试剂槽-巴氏吸管-5ml样品瓶-SBS液氮冻存管-上海希言科学仪器有限公司 | 镀锌角钢_槽钢_扁钢_圆钢_方矩管厂家_镀锌花纹板-海邦钢铁(天津)有限公司 | Dataforth隔离信号调理模块-信号放大模块-加速度振动传感器-北京康泰电子有限公司 | EDLC超级法拉电容器_LIC锂离子超级电容_超级电容模组_软包单体电容电池_轴向薄膜电力电容器_深圳佳名兴电容有限公司_JMX专注中高端品牌电容生产厂家 | 婚博会2024时间表_婚博会门票领取_婚博会地址-婚博会官网 | 大流量卧式砂磨机_强力分散机_双行星双动力混合机_同心双轴搅拌机-莱州市龙跃化工机械有限公司 | 精密模具加工制造 - 富东懿| 工程管道/塑料管材/pvc排水管/ppr给水管/pe双壁波纹管等品牌管材批发厂家-河南洁尔康建材 | 档案密集柜_手动密集柜_智能密集柜_内蒙古档案密集柜-盛隆柜业内蒙古密集柜直销中心 | 磁棒电感生产厂家-电感器厂家-电感定制-贴片功率电感供应商-棒形电感生产厂家-苏州谷景电子有限公司 | 校园文化空间设计-数字化|中医文化空间设计-党建|法治廉政主题文化空间施工-山东锐尚文化传播公司 | 上海律师咨询_上海法律在线咨询免费_找对口律师上策法网-策法网 广东高华家具-公寓床|学生宿舍双层铁床厂家【质保十年】 | 内窥镜-工业内窥镜厂家【上海修远仪器仪表有限公司】 | 磁力链接搜索神器_BT磁力狗_CILIMAO磁力猫_高效磁力搜索引擎2024 | 蒸压釜_蒸养釜_蒸压釜厂家-山东鑫泰鑫智能装备有限公司 | 东莞压铸厂_精密压铸_锌合金压铸_铝合金压铸_压铸件加工_东莞祥宇金属制品 | 解放卡车|出口|济南重汽|报价大全|山东三维商贸有限公司 | 杭州中央空调维修_冷却塔/新风机柜/热水器/锅炉除垢清洗_除垢剂_风机盘管_冷凝器清洗-杭州亿诺能源有限公司 | 卷筒电缆-拖链电缆-特种柔性扁平电缆定制厂家「上海缆胜」 | 环氧乙烷灭菌器_压力蒸汽灭菌器_低温等离子过氧化氢灭菌器 _低温蒸汽甲醛灭菌器_清洗工作站_医用干燥柜_灭菌耗材-环氧乙烷灭菌器_脉动真空压力蒸汽灭菌器_低温等离子灭菌设备_河南省三强医疗器械有限责任公司 | 缠膜机|缠绕包装机|无纺布包装机-济南达伦特机械设备有限公司 |