多线程并发的情况单元测试编写

单元测试怎么模拟多个线程同时操作时的情况呢?结果怎么验证?

我的方法是启动多个线程,用一个计数器CountDownLatch去等所有的线程执行完了,然后对结果进行校验。

比如一个list,可能会有多个线程执行add方法,那么执行完成之后,将list.size最为结果进行校验:

    @Test
    public void addStatusChangedListener2() throws InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(1000);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 1000; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Status.shared().addStatusChangedListener(changedListener);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
        }
        countDownLatch.await();
        executorService.shutdown();

        assertThat(getListSize(Status.shared(), "mStatusChangeListeners"), is(1000));
    }

其中getListSize是自定义的方法,通过反射方式拿到list的size:

    private int getListSize(Object statusInst, String listName) {
        try {
            Field field = Status.class.getDeclaredField(listName);
            field.setAccessible(true);
            Object futureList = field.get(statusInst);

            Method method = futureList.getClass().getMethod("size");
            return (int) method.invoke(futureList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //异常情况
        return -1;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容