Unit test error if an exception is thrown in another thread

Currently, when I need to skip a test in response to an exception thrown in another thread, I write something like this:

package com.example;

import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Test;

import static java.util.Arrays.asList;
import static java.util.Collections.synchronizedList;
import static org.testng.Assert.fail;

public final class T {
  @Test
  public void testFailureFromLambda() throws Throwable {
    final List<Throwable> errors = synchronizedList(new ArrayList<>());

    asList("0", "1", "2").parallelStream().forEach(s -> {
      try {
        /*
         * The actual code under test here.
         */
        throw new Exception("Error " + s);
      } catch (final Throwable t) {
        errors.add(t);
      }
    });

    if (!errors.isEmpty()) {
      errors.forEach(Throwable::printStackTrace);

      final Throwable firstError = errors.iterator().next();
      fail(firstError.getMessage(), firstError);
    }
  }
}

The synchronized list can be replaced by AtomicReference<Throwable>, but in general the code remains almost the same.

Is there any standard (and less verbose) way to do the same using any of the test frameworks available in Java ( TestNG , JUnit , Hamcrest , AssertJ , etc.)?

+4
source share
1 answer

TestNG , . , JUnit, errored, .

Streams, RuntimeException, Java . TestNG .

:

@Test
public void testFailureFromLambdaRefactored() {
    asList("0", "1", "2").parallelStream().forEach(s -> {
        try {
        /*
        * The actual code under test here.
        */
            if (s.equals("2")) {
                throw new Exception("Error " + s);
            }
        } catch (final Throwable t) {
            throw new RuntimeException(t);
        }
    });
}

, . , , , @Test, ExecutorService.

:

@Test
public void testFailureInAnotherThread() throws InterruptedException, ExecutionException {
    List<String> list = asList("0", "1", "2");
    ExecutorService service = Executors.newFixedThreadPool(2);
    List<Future<Void>> futures = service.invokeAll(Arrays.asList(new Worker(list)));
    for (Future future : futures) {
        future.get();
    }

}

public static class Worker implements Callable<Void> {
    private List<String> list;

    public Worker(List<String> list) {
        this.list = list;
    }

    @Override
    public Void call() throws Exception {
        for (String s : list) {
            if (s.equals("2")) {
                throw new Exception("Error " + s);
            }
        }
        return null;
    }
}
+4

Source: https://habr.com/ru/post/1683973/


All Articles