ฉันกำลังพยายามเยาะเย้ยวิธี SAXParser.parse(...) โดยใช้ JMockit
ฉันสามารถตั้งค่าความคาดหวังสำหรับลายเซ็นเมธอด parse (InputStream, DefaultHandler) ได้สำเร็จ แต่เมื่อฉันพยายามจำลองลายเซ็น parse (InputSource, DefaultHandler) JMockit จะไม่เห็นการร้องขอและส่งข้อยกเว้น MissingInvocation
ตัวอย่างต่อไปนี้แสดงกรณีทดสอบสองกรณี กรณีหนึ่งล้อเลียนรสชาติของ InputSource และอีกกรณีหนึ่งล้อเลียนรสชาติของ InputStream:
public class SAXTest {
@Test(expected=RuntimeException.class)
public void testParseInputSource(@Mocked final SAXParser saxParser) throws Exception {
new Expectations() {{
saxParser.parse((InputSource) any, (DefaultHandler) any); result = new RuntimeException("Fail now");
}};
SAXParser p = SAXParserFactory.newInstance().newSAXParser();
InputSource isource = new InputSource(new StringReader("<test/>"));
p.parse(isource, new DefaultHandler());
}
@Test(expected=RuntimeException.class)
public void testParseInputStream(@Mocked final SAXParser saxParser) throws Exception {
new Expectations() {{
saxParser.parse((InputStream) any, (DefaultHandler) any); result = new RuntimeException("Fail now");
}};
SAXParser p = SAXParserFactory.newInstance().newSAXParser();
InputStream istream = new ByteArrayInputStream("</test>".getBytes());
p.parse(istream, new DefaultHandler());
}
}
การรัน testcase ส่งผลให้:
JUnit version 4.12
E.
Time: 0.069
There was 1 failure:
1) testParseInputSource(SAXTest)
java.lang.Exception: Unexpected exception, expected<java.lang.RuntimeException> but was<mockit.internal.MissingInvocation>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
...
Caused by: Missing 1 invocation to:
javax.xml.parsers.SAXParser#parse(any org.xml.sax.InputSource, any org.xml.sax.helpers.DefaultHandler)
on mock instance: $Subclass_SAXParser_param0@490d6c15
Caused by: Missing invocations
at javax.xml.parsers.SAXParser.parse(SAXParser.java)
at SAXTest$1.<init>(SAXTest.java:20)
at SAXTest.testParseInputSource(SAXTest.java:19)
FAILURES!!!
Tests run: 2, Failures: 1
อย่างที่คุณเห็น เวอร์ชัน InputSource ล้มเหลว ในขณะที่เวอร์ชัน InputStream ทำงานตามที่คาดไว้
ฉันใช้ Junit 4.12 และ JMockit 1.32