java - 使用 JUnit 在多线程环境中测试方法行为?

标签 java unit-testing tdd junit4

对于给定的方法,我想编写测试用例以查看它在多个线程同时运行时的行为。可能听起来很愚蠢,但只是想知道是否有可能创造任何这样的场景?

最佳答案

最近我在一些代码中是这样实现的:

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.junit.Assert.*;
public class UtilTest
{
    private final static int TEST_THREAD_COUNT = 10;
    private volatile int threadsRun = 0;
    private volatile List<String> nonUniqueIds = new ArrayList<>();

    @Test
    public void testUniqueIdGeneration()
    {
        final ExecutorService pool = Executors.newFixedThreadPool(TEST_THREAD_COUNT);
        Runnable r = new Runnable()
        {
            @Override
            public void run()
            {
                List<String> doneIds = new ArrayList<>();
                for (int i = 1; i <= 100; i++)
                {
                    String id = Util.generateId();
                    if (doneIds.contains(id))
                    {
                        nonUniqueIds.add(id);
                        break;
                    }
                    doneIds.add(id);
                }
                threadsRun++;
                if (threadsRun >= TEST_THREAD_COUNT)
                    pool.shutdown();
            }
        };

        for (int i = 0; i < TEST_THREAD_COUNT; i++)
        {
            pool.submit(r);
        }
        while (! pool.isShutdown())
        {
            //stay alive
        }

        if (nonUniqueIds.isEmpty() )
            return;

        for (String id: nonUniqueIds)
        {
            System.out.println("Non unique id: " + id);
        }
        assertTrue("Non unique ids found", false);
    }
}

关于java - 使用 JUnit 在多线程环境中测试方法行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18580896/

相关文章:

.net - 可以更改批准测试的文件名

c# - 使用最小起订量模拟嵌套依赖关系

c# - TDD : Any pattern for constant testing?

c - 正则表达式测试台

php - 从哪里开始开发第一个数据库驱动的 Web 应用程序(长问题)?

java - 使用 gradle-retrolambda 和 Lightweight-Stream-API 在 Android 中过滤对象列表

java - 全局异常处理(非 REST Controller 代码)

java - Android 中的输入验证

java - 在@Before 之外使用@InjectMocks

java - Rest Api 调用使用 Spring Oauth2 给出错误 400