2012-07-10 79 views
3

为了更好地处理异常,我在jUnit中发现了@Rule注释。 有没有办法检查错误代码?在junit中检查@rule的错误代码

目前我的代码看起来像(不@rule):

@Test 
    public void checkNullObject() { 
    MyClass myClass= null; 
    try { 
     MyCustomClass.get(null); // it throws custom exception when null is passed 
    } catch (CustomException e) { // error code is error.reason.null 
     Assert.assertSame("error.reason.null", e.getInformationCode()); 
    } 
    } 

但随着使用@Rule,我做以下操作:

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

     @Test 
     public void checkNullObject() throws CustomException { 
     exception.expect(CustomException .class); 
     exception.expectMessage("Input object is null."); 
     MyClass myClass= null; 
     MyCustomClass.get(null); 

     } 

但是,我想要做的事象下面这样:

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

     @Test 
     public void checkNullObject() throws CustomException { 
     exception.expect(CustomException .class); 
     //currently below line is not legal. But I need to check errorcode. 
     exception.errorCode("error.reason.null"); 
     MyClass myClass= null; 
     MyCustomClass.get(null); 

     } 

回答

4

您可以在的规则上使用自定义匹配器方法。

例如:

public class ErrorCodeMatcher extends BaseMatcher<CustomException> { 
    private final String expectedCode; 

    public ErrorCodeMatcher(String expectedCode) { 
    this.expectedCode = expectedCode; 
    } 

    @Override 
    public boolean matches(Object item) { 
    CustomException e = (CustomException)item; 
    return expectedCode.equals(e.getInformationCode()); 
    } 
} 

,并在测试:

exception.expect(new ErrorCodeMatcher("error.reason.null")); 
+0

非常感谢使用。我正在寻找类似的东西。我希望这会起作用。 :) – 2012-07-10 13:20:10

+0

有一个疑问:BaseMatcher是来自org.hamcrest吗? – 2012-07-10 13:28:53

+0

是的,它应该包含在jUnit中。 – casablanca 2012-07-10 13:31:27

1

您还可以看到如何expect(Matcher<?> matcher)内已ExpectedException.java source

private Matcher<Throwable> hasMessage(final Matcher<String> matcher) { 
    return new TypeSafeMatcher<Throwable>() { 
     @Override 
     public boolean matchesSafely(Throwable item) { 
     return matcher.matches(item.getMessage()); 
     } 
    }; 
} 

    public void expectMessage(Matcher<String> matcher) { 
     expect(hasMessage(matcher)); 
} 
+0

在我的示例中,TypeSafeMatcher比BaseMatcher更好。 – casablanca 2012-07-10 13:31:58