如何使用 JUnit 测试注释断言 IOException 消息?
How do I assert an IOException message with JUnit Test annotation?
当我使用 @Rule with ExpectedException as shown below in 1st (adapted post) 时,我在 (*) 处的 Class2testTest class 中收到错误 "Unhandled Exception type"。
package class2test;
import java.io.IOException;
public class Class2test {
public Class2test() throws IOException{
throw new IOException("j");
}
}
package test;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import class2test.Class2test;
public class Class2testTest {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Test
public void test() {
expectedEx.expect(IOException.class);
expectedEx.expectMessage("j");
new Class2test(); //(*)
}
}
我不明白这一点:adapted post 是可重现的(使用 RuntimeException 而不是 IOException 它有效)。
您应该在方法的签名中指定抛出的异常:
public void test() throws Exception {
当我使用 @Rule with ExpectedException as shown below in 1st (adapted post) 时,我在 (*) 处的 Class2testTest class 中收到错误 "Unhandled Exception type"。
package class2test;
import java.io.IOException;
public class Class2test {
public Class2test() throws IOException{
throw new IOException("j");
}
}
package test;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import class2test.Class2test;
public class Class2testTest {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Test
public void test() {
expectedEx.expect(IOException.class);
expectedEx.expectMessage("j");
new Class2test(); //(*)
}
}
我不明白这一点:adapted post 是可重现的(使用 RuntimeException 而不是 IOException 它有效)。
您应该在方法的签名中指定抛出的异常:
public void test() throws Exception {