使用JUnit 4测试自定义异常的错误代码

时间:2017-04-03 07:50:23

标签: java junit junit4 junit-rule

我想测试异常的返回码。这是我的生产代码:

public static Set<String> getImgStr(String htmlStr) {
    Set<String> pics = new HashSet<>();
    String img = "";
    Pattern p_image;
    Matcher m_image;
    String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
    p_image = Pattern.compile
            (regEx_img, Pattern.CASE_INSENSITIVE);
    m_image = p_image.matcher(htmlStr);
    while (m_image.find()) {
        img = m_image.group();
        Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
        while (m.find()) {
            pics.add(m.group(1));
        }
    }
    return pics;
}

相应的例外:

class A {
  try {
    something...
  }
  catch (Exception e)
  {
    throw new MyExceptionClass(INTERNAL_ERROR_CODE, e);
  }
}

我的单元测试:

class MyExceptionClass extends ... {
  private errorCode;

  public MyExceptionClass(int errorCode){
    this.errorCode = errorCode;
  }

  public getErrorCode(){ 
    return this.errorCode;
  }
}

3 个答案:

答案 0 :(得分:6)

简单:

 @Test 
 public void whenSerialNumberIsEmpty_shouldThrowSerialNumberInvalid() throws Exception {
  try{
     whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode();     
     fail("should have thrown");
  }
  catch (MyExceptionClass e){
     assertThat(e.getCode(), is(MyExceptionClass.INTERNAL_ERROR_CODE));
  }

这就是你需要的所有内容:

  • 您不希望期待该特定异常,因为您希望检查其中的某些属性
  • 您知道想要输入那个特定的catch块;因此,当电话没有抛出时,你就会失败
  • 您不需要任何其他检查 - 当方法抛出任何其他异常时,JUnit会将此报告为错误

答案 1 :(得分:3)

您可以使用hamcres匹配器检查它,只要thrown.expect超载就可以Matcher

thrown.expect(CombinableMatcher.both(
           CoreMatchers.is(CoreMatchers.instanceOf(MyExceptionClass.class)))
           .and(Matchers.hasProperty("errorCode", CoreMatchers.is(123))));

请注意,您需要将hamcrest匹配器添加到依赖项中。 JUnit中包含的核心匹配是不够的。

或者,如果您不想使用CombinableMatcher:

thrown.expect(CoreMatchers.instanceOf(MyExceptionClass.class));
thrown.expect(Matchers.hasProperty("errorCode", CoreMatchers.is(123));

此外,您不需要(expected = MyExceptionClass.class) @Test注释声明

答案 2 :(得分:1)

扩展Sergii的答案,您可以编写一个自定义匹配器来清理更多内容。

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

public class CustomMatcher extends TypeSafeMatcher<CustomException> {

    public static CustomMatcher hasCode(String item) {
        return new CustomMatcher(item);
    }

    private String foundErrorCode;
    private final String expectedErrorCode;

    private CustomMatcher(String expectedErrorCode) {
        this.expectedErrorCode = expectedErrorCode;
    }

    @Override
    protected boolean matchesSafely(final CustomException exception) {
        foundErrorCode = exception.getErrorCode();
        return foundErrorCode.equalsIgnoreCase(expectedErrorCode);
    }

    @Override
    public void describeTo(Description description) {
        description.appendValue(foundErrorCode)
                .appendText(" was not found instead of ")
                .appendValue(expectedErrorCode);
    }
}

然后可以按照以下方式检查错误代码:

import org.junit.rules.ExpectedException;

public class MyObjTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void someMethodThatThrowsCustomException() {
        thrown.expect(CustomException.class);
        thrown.expect(CustomMatcher.hasCode("110501"));

        MyObj obj = new MyObj();
        obj.methodThatThrowsCustomException();
    }
}

参考:https://dzone.com/articles/testing-custom-exceptions