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

2020-05-20  本文已影响0人  孤舟一夜大侠

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

我的方法是启动多个线程,用一个计数器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;
    }
上一篇下一篇

猜你喜欢

热点阅读