有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

测试并发性的javajunit

我正在尝试测试java。util。同时发生的当通过多个线程访问时,ConcurrentLinkedQueue。下面提到的是我的Junit测试,它使用RepeatedTest在两个并发线程中运行。我的问题是:例如在ConcurrentLinkedQueue上使用RepeatedTest测试并发性是否正确?下面提到了源代码

谢谢

import java.util.concurrent.ConcurrentLinkedQueue;
import junit.extensions.ActiveTestSuite;
import junit.extensions.RepeatedTest;
import junit.extensions.TestSetup;
import junit.framework.TestCase;

public class TestNonBlockingConcurrentQueue extends TestCase{

private static ConcurrentLinkedQueue clq;

public void testPut() throws Exception {
    int messageCounter = 0;
    for(;messageCounter <10000; messageCounter++){
        clq.offer(messageCounter);
    }
    assertEquals(clq.size(), messageCounter);
}

public void testGet() throws Exception {
    while(!clq.isEmpty()){
        clq.poll();
    }
    assertEquals("Size should be zero", clq.size(), 0);
}

public static junit.framework.Test suite( ) {
    ActiveTestSuite ats = new ActiveTestSuite();

    TestSetup setup = new TestSetup(ats) {
       protected void setUp() throws Exception {
            System.out.println("Creating ConcurrentLinkedQueue..");
            clq = new ConcurrentLinkedQueue();
        }
        protected void tearDown(  ) throws Exception {
            clq = null;
        }
    };
    ats.addTest(new RepeatedTest(new TestNonBlockingConcurrentQueue("testPut"), 2));
    ats.addTest(new RepeatedTest(new TestNonBlockingConcurrentQueue("testGet"), 2));
    return setup;

}

public TestNonBlockingConcurrentQueue(String testName){
    super(testName);
}

共 (2) 个答案

  1. # 2 楼答案

    您永远无法真正运行测试来检查并发性问题。在特定的测试机器上(在给定的操作系统上,有一定数量的内核或处理器,甚至只有其他进程同时运行)没有出现问题,这并不意味着没有问题