微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 hemcrest 在 JUnit5 中参数化异常?

如何解决如何使用 hemcrest 在 JUnit5 中参数化异常?

我想使用 hemcrest 的一种参数化测试来测试所有不同的异常。所以这意味着 Exception1.class,Exception2.class 应该是参数。我如何参数化它们,并通过使用 hemcrest 来实现?

解决方法

假设您的被测方法根据场景返回不同的异常,您应该参数化夹具(对于场景)和预期(对于异常)。

使用Foo.foo(String input)方法进行测试,例如:

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");
    }

  }
}

它可能看起来像:

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"));

  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。