0

i want to test all different exceptions with one parameterized test using hemcrest for one method. So that means that Exception1.class, Exception2.class should be parameters. How do i parameterize them, and do it by using hemcrest?

1 Answers1

1

Suppose your method under test returns distinct exceptions according to scenarios, you should parameterize both fixture (for scenarios) and expected (for exceptions).

With a Foo.foo(String input) method to test such as :

import java.io.FileNotFoundException;

public class Foo {
  public void foo(String input) throws FileNotFoundException {

    if ("a bad bar".equals(input)){
       throw new IllegalArgumentException("bar value is incorrect");
    }

    if ("inexisting-bar-file".equals(input)){
      throw new FileNotFoundException("bar file doesn't exit");
    }

  }
}

it could look like :

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.stream.Stream;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.api.Assertions;

public class FooTest {


  @ParameterizedTest
  @MethodSource("fooFixture")
  void foo(String input, Class<Exception> expectedExceptionClass, String expectedExceptionMessage) {
    Assertions.assertThrows(
        expectedExceptionClass,
        () -> new Foo().foo(input),
        expectedExceptionMessage
    );

  }

  private static Stream<Arguments> fooFixture() {
    return Stream.of(
        Arguments.of("a bad bar", IllegalArgumentException.class, "bar value is incorrect"), Arguments.of("inexisting-bar-file", FileNotFoundException.class, "bar file doesn't exit"));

  }
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215