Gui*_*ume 8 java junit junit4 junit-rule
我想测试异常的返回码.这是我的生产代码:
class A {
try {
something...
}
catch (Exception e)
{
throw new MyExceptionClass(INTERNAL_ERROR_CODE, e);
}
}
Run Code Online (Sandbox Code Playgroud)
和相应的例外:
class MyExceptionClass extends ... {
private errorCode;
public MyExceptionClass(int errorCode){
this.errorCode = errorCode;
}
public getErrorCode(){
return this.errorCode;
}
}
Run Code Online (Sandbox Code Playgroud)
我的单元测试:
public class AUnitTests{
@Rule
public ExpectedException thrown= ExpectedException.none();
@Test (expected = MyExceptionClass.class,
public void whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode() throws Exception {
thrown.expect(MyExceptionClass.class);
??? expected return code INTERNAL_ERROR_CODE ???
something();
}
}
Run Code Online (Sandbox Code Playgroud)
只要thrown.expect
接收过载,您就可以使用 hamcres 匹配器检查它Matcher
thrown.expect(CombinableMatcher.both(
CoreMatchers.is(CoreMatchers.instanceOf(MyExceptionClass.class)))
.and(Matchers.hasProperty("errorCode", CoreMatchers.is(123))));
Run Code Online (Sandbox Code Playgroud)
请注意,您需要将 hamcrest 匹配器添加到您的依赖项中。包含在 JUnit 中的核心匹配是不够的。
或者,如果您不想使用 CombinableMatcher:
thrown.expect(CoreMatchers.instanceOf(MyExceptionClass.class));
thrown.expect(Matchers.hasProperty("errorCode", CoreMatchers.is(123));
Run Code Online (Sandbox Code Playgroud)
此外,您不需要(expected = MyExceptionClass.class)
声明@Test
注释
简单:
@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));
}
Run Code Online (Sandbox Code Playgroud)
这就是你需要的一切:
归档时间: |
|
查看次数: |
3492 次 |
最近记录: |