如何在JUnit测试中为多个文件执行测试

时间:2016-01-06 13:06:58

标签: java junit junit4

我想在Spring Framework中使用JUnit测试来测试多个文件。到目前为止,我的进步是可以使用Spring Framework global.properties从目录中读取文件。我的测试类从目录中读取文件,并在@Before中读取这些文件并逐个发送到我的@Test函数以生成测试结果。

@RunWith(MultiThreadedRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"})
public class FullCycleTest {


@Before  
public void beforeUploadTest() throws Exception {


    new TestContextManager(getClass()).prepareTestInstance(this); // TestContextManager is responsible for managing Spring TestContext Framework
    this.resourcesTest = new ResourcesTest();   // get instance of ResourceTest class
    this.uploadTest = new UploadandJobTest();
    this.folder = new File(resourcesTest.basePath());
    this.file = new ArrayList<>();
    File[] fileEntry = folder.listFiles();
    this.uploadControllerTest = new UploadControllerTest();
    this.uploadResult = new UploadJSON();

    /******File upload read*****/

    for (int i = 0; i < fileEntry.length; i++) {
        if (fileEntry[i].exists()) { 
            file.add(String.valueOf(fileEntry[i]));
            System.out.println("Testing for file" + file);

        }
    }
}

@Test
public void UploadandJobTest() {

    for (String s : file) {

        uploadTest.uploadAndJobTest(s);
        uploadControllerTest.upload_stl_response(s);
    }
}

所以在@Test中我可以在测试中逐个测试每个文件。我想要做的是同时测试所有文件而无需等待完成每个文件。我知道TestSuite可以在TestSuite中执行所有测试。就我而言,这没用。有没有办法以编程方式创建@Test而不使用任何注释@Test ??谢谢

1 个答案:

答案 0 :(得分:1)

我过去使用过参数化测试,效果很好,而且这样可以让@RunWith(Parallelized.class)使用它。

以下是示例:

@RunWith(Parallelized.class)
public class FeatureTest
{
   // same class body as above
}

您只需要参数化跑步者的简单扩展:

public class Parallelized extends Parameterized
{

    private static class ThreadPoolScheduler implements RunnerScheduler
    {
        private ExecutorService executor; 

        public ThreadPoolScheduler()
        {
            String threads = System.getProperty("junit.parallel.threads", "16");
            int numThreads = Integer.parseInt(threads);
            executor = Executors.newFixedThreadPool(numThreads);
        }

        @Override
        public void finished()
        {
            executor.shutdown();
            try
            {
                executor.awaitTermination(10, TimeUnit.MINUTES);
            }
            catch (InterruptedException exc)
            {
                throw new RuntimeException(exc);
            }
        }

        @Override
        public void schedule(Runnable childStatement)
        {
            executor.submit(childStatement);
        }
    }

    public Parallelized(Class klass) throws Throwable
    {
        super(klass);
        setScheduler(new ThreadPoolScheduler());
    }
}

此处有更多信息http://hwellmann.blogspot.com/2009/12/running-parameterized-junit-tests-in.html

相关问题