單元測試怎么模擬多個線程同時操作時的情況呢?結果怎么驗證?
我的方法是啟動多個線程屈嗤,用一個計數(shù)器CountDownLatch去等所有的線程執(zhí)行完了,然后對結果進行校驗吊输。
比如一個list饶号,可能會有多個線程執(zhí)行add方法,那么執(zhí)行完成之后季蚂,將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;
}