使用JUnit4+测试异常处理是否如预期的那样的方法可能是这样的(注意,如果没有抛出异常,则需要使测试失败)。
@Test
public void testWriteToOutputStreamExceptionHandling() {
//Dummy object for testing
OutputStream exceptionThrowingOutputStream = new OutputStream() {
public void write(byte[] b) throws IOException {
throw new IOException(); //always throw exception
}
public void write(int b) {} //need to overwrite abstract method
};
try {
YourClass.writeToOutputStream(new byte[0], exceptionThrowingOutputStream);
fail("NetModelStreamingException expected");
}
catch (NetModelStreamingException e) {
//ok
}
}
如果在其他测试方法中也需要该虚拟对象,则应在测试用例中声明成员变量,并在
setUp
-方法的注释为
@Before
. 而且,你可以隐藏
try-catch
-通过在
@Test
注解。
这样,代码将如下所示:
private OutputStream exceptionThrowingOutputStream;
@Before
public void setUp() throws Exception {
exceptionThrowingOutputStream = new OutputStream() {
@Override
public void write(byte[] b) throws IOException {
throw new IOException();
}
@Override
public void write(int b) {}
};
}
@Test(expected = NetModelStreamingException.class)
public void testWriteToOutputStreamExceptionHandling() throws NetModelStreamingException {
YourClass.writeToOutputStream(new byte[0], exceptionThrowingOutputStream);
}