繁体   English   中英

如何编写测试并发不变量的单元测试

[英]How to write unit tests that tests concurrency invariants

关于这个问题还有其他问题,但我正在试图如何处理这样的单元测试:

 public class Semaphore extends Lock {
        private AtomicInteger semaphore = new AtomicInteger(0);
        public synchronized boolean available() {
                return semaphore.intValue() == 0;
        }
        public synchronized void acquire() {
            semaphore.incrementAndGet();

        }
        public synchronized void release() {
            semaphore.decrementAndGet();
        }
    }

这是我的朴素锁定机制(仅用于学习目的)。 我该如何测试这个线程的安全性? 我知道在单元测试并发代码方面没有任何保证,但是我怎样才能编写单元测试ATTEMPTS来测试这种锁定机制中固有的明显不变量?

我想自从我做了一些研究后,我会回答我自己的问题。 有一个很棒的框架叫做MultithreadedTC 它允许您设置如下测试:

public class SafeSemaphoreTest extends MultithreadedTestCase {

    private SafeSemaphore semaphore;
    AtomicInteger ai = new AtomicInteger(0);

    @Override
    public void initialize() {
        semaphore = new SafeSemaphore();
    }


    public void thread1() throws InterruptedException {

        assertTick(0);

        semaphore.acquire();
        waitForTick(2);
        assertTick(2);

        semaphore.acquire();
        assertEquals(semaphore.getValue(), 2);
        assertEquals(semaphore.getValue()==3, false);
        semaphore.release();
        semaphore.release();

    }

    public void thread2() throws InterruptedException {
        waitForTick(1);
        assertTick(1);
        assertEquals(semaphore.available(), false);
        waitForTick(3);
        assertTick(3);
        assertEquals(semaphore.available(), true);

    }

}

其中waitForTick(int)调用生成当前Thread块直到达到tick。 为了更好的JUnit集成,甚至还有一些开发使它更现代化: http//janvanbesien.blogspot.com/2009/06/modernizing-multithreadedtc-junit-4.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM