2

我正在尝试学习 JUnit,并希望将其扩展为以多线程方式进行测试。

我要测试的类是 PrimeNumberValidator。这只是测试传入的数字是否为素数。

package com;

public class PrimeNumberValidator {
    public Boolean validate(final Integer primeNumber) {
        System.out.println("Validating .............:" + primeNumber);
        for (int i = 2; i < (primeNumber / 2); i++) {
            if (primeNumber % i == 0) {
                return false;
            }
        }

        return true;
    }
}


PrimeNumberValidatorTest 是测试类。测试数据中的 2 个是错误的,我特意这样做是为了测试是否失败。
测试方法 testPrimeNumberValidator 运行良好。但是,多线程版本
testMultiThreadedPrimeNumberValidator 即使是错误的数据也总是说“通过”。
为什么会这样?
如何解决这个问题?

package com;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class PrimeNumberValidatorTest {
    private Integer primeNumber;
    private Boolean expectedValidation;
    private PrimeNumberValidator primeNumberValidator;

    @Before
    public void initialize() {
    primeNumberValidator = new PrimeNumberValidator();
    }

    // Each parameter should be placed as an argument here
    // Every time runner triggers, it will pass the arguments from parameters we defined
    public PrimeNumberValidatorTest(Integer primeNumber, Boolean expectedValidation) {
    this.primeNumber = primeNumber;
    this.expectedValidation = expectedValidation;
    }

    @Parameterized.Parameters
    public static Collection primeNumbers() {
    return Arrays.asList(new Object[][] {
        { 2, Boolean.FALSE},// 2 is prime so Test should fail
        { 6, Boolean.FALSE}, //is NOT prime so test should pass
        { 19, Boolean.TRUE},//is prime so test should pass
        { 22, Boolean.TRUE} //is NOT prime so test should fail
    });
    }

    // This test will run 4 times since we have 4 parameters defined
    @Test
    public void testPrimeNumberValidator() {
    assertEquals(expectedValidation, primeNumberValidator.validate(primeNumber));
    }

    @Test
    public void testMultiThreadedPrimeNumberValidator() {

    ExecutorService executor = Executors.newFixedThreadPool(100);
    executor.submit(new Runnable() {

        public void run() {
        for (int i = 0; i < 100; i++) {
            assertEquals(expectedValidation, primeNumberValidator.validate(primeNumber));
        }   
        }
    }); 
    }
}

参考
http://www.youtube.com/watch?v=wDN_EYUvUq0 ,如
在多线程环境中使用 JUnit 的奇怪问题之一中提到的,尝试如下。
抛出异常,但 JUnit 不报告失败 :(

package com;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class PrimeNumberValidatorTest {
    volatile Exception exception;
    volatile Error error;

    private Integer primeNumber;
    private Boolean expectedValidation;
    private PrimeNumberValidator primeNumberValidator;

    @Before
    public void initialize() {
    primeNumberValidator = new PrimeNumberValidator();
    }

    // Each parameter should be placed as an argument here
    // Every time runner triggers, it will pass the arguments from parameters we defined
    public PrimeNumberValidatorTest(Integer primeNumber, Boolean expectedValidation) {
    this.primeNumber = primeNumber;
    this.expectedValidation = expectedValidation;
    }

    @Parameterized.Parameters
    public static Collection primeNumbers() {
    return Arrays.asList(new Object[][] {
        { 2, Boolean.FALSE},// 2 is prime so Test should fail
        { 6, Boolean.FALSE}, //is NOT prime so test should pass
        { 19, Boolean.TRUE},//is prime so test should pass
        { 22, Boolean.TRUE} //is NOT prime so test should fail
    });
    }

    // This test will run 4 times since we have 4 parameters defined
    @Test
    @Ignore
    public void testPrimeNumberValidator() {
    assertEquals(expectedValidation, primeNumberValidator.validate(primeNumber));
    }

    @Test
    public void testMultiThreadedPrimeNumberValidator() {

    ExecutorService executor = Executors.newFixedThreadPool(100);
    executor.submit(new Runnable() {

        public void run() {
        for (int i = 0; i < 1; i++) {
            try{
                assertEquals(expectedValidation, primeNumberValidator.validate(primeNumber));
            }catch(Error e){
                System.out.println("error thrown :" + e);
                error =e;
            }catch(Exception e){
                exception=e;
                System.out.println("exception thrown :" + e);
            }
        }   
        }
    }); 
    }

    @After
    public void runAfterEveryTest() throws Exception{
    if(null != error){
        System.out.println("runAfterEveryTest throwing error...............");
        throw error;
    }
    if(null != exception){
        System.out.println("runAfterEveryTest throwing exception...............");
        throw exception;
    }
    }
}
4

2 回答 2

0

它已通过以下代码解决。Future 相关代码的添加使其工作。

@Test
public void testMultiThreadedPrimeNumberValidator() throws InterruptedException, ExecutionException {

    ExecutorService executor = Executors.newFixedThreadPool(100);
    Future future = executor.submit(new Runnable() {

        public void run() {
            for (int i = 0; i < 10; i++) {
                try{
                    assertEquals(expectedValidation, primeNumberValidator.validate(primeNumber));
                }catch(Error e){
                    System.out.println("error thrown :" + e);
                    //error =e;
                    System.out.println("error set to :" + e);
                }catch(Exception e){
                    System.out.println("exception thrown :" + e);
                    //exception=e;
                    System.out.println("Exception set to :" + e);
                }
            }   
        }
    }); 
    future.get();
}
于 2013-09-19T17:40:43.617 回答
0

多线程总是通过的原因如下:

  • 首先,测试方法不等待多个线程完成,因此该@Test方法在报告任何错误之前退出
  • 其次,测试的工作方式是 assert 方法抛出异常。JUnit 框架通过包装该方法来捕获此异常,@Test如果抛出意外异常,则测试失败。但是,在多线程测试中,该@Test方法不会引发异常,因为它们是在线程内引发的,并且测试方法不会对此进行检查。这部分的一种解决方案是使用ErrorCollector
于 2013-09-19T11:04:53.323 回答