异常的Java单元测试

时间:2013-08-26 15:51:31

标签: junit powermock

public Document query(String uri) throws IOException, IllegalArgumentException
{

    final HttpGet httpget = new HttpGet(uri);
    final HttpResponse response = httpclient.execute(httpget);
    final HttpEntity entity = response.getEntity();
    Document doc = null;
    try
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(entity.getContent());
    }
    catch (SAXException e)
    {

        LOGGER.error(e);
        throw new IllegalArgumentException("parse error" + e);
    }
    catch (ParserConfigurationException e)
    {

        LOGGER.error(e);
        throw new IllegalArgumentException("parameter factor is invalid: " + e);
    }
    catch (IllegalStateException e)
    {

        LOGGER.error(e);
        throw new IllegalArgumentException("null entity contetents" + e);
    }

    return doc;
}


 @Test(expected = IllegalArgumentException.class)
public void testQuery_ParseExceptionThrown() throws Exception
{
    String uri ="some uri";
    EasyMock.expect(httpClient.execute(EasyMock.isA(HttpGet.class))).andReturn(mockResponse);
    EasyMock.expect(mockResponse.getEntity()).andReturn(mockEntity);
    EasyMock.expect(mockEntity.getContent()).andReturn(new ByteArrayInputStream(REPSONSE_EXAMPLE.getBytes()));
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();


    EasyMock.expect(builder.parse(EasyMock.isA(InputStream.class))).andThrow(
            new IllegalArgumentException("expected"));
    EasyMock.replay();
    class.query(uri);

}

错误:

java.lang.IllegalStateException: calling verify is not allowed in record state
    at org.easymock.internal.MocksControl.verify(MocksControl.java:181)
    at org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl.verify(EasyMockMethodInvocationControl.java:120)
    at org.powermock.api.easymock.PowerMock.verify(PowerMock.java:1650)
    at org.powermock.api.easymock.PowerMock.verifyAll(PowerMock.java:1586)
    at com.amazon.ams.test.AbstractUnitTest.verifyMocks(AbstractUnitTest.java:78)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.internal.runners.MethodRoadie.runAfters(MethodRoadie.java:145)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:99)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:296)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:112)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:73)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:284)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:209)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:148)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:102)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:42)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

我不断收到一些错误,比如

java.lang.AssertionError: Expected exception: org.xml.sax.SAXException
java.lang.IllegalStateException: calling verify is not allowed in record state

我需要编写3个例子来编写Junit测试以进入异常。有谁知道如何使用powermock或easymock类为它编写单元测试?

1 个答案:

答案 0 :(得分:1)

如果您使用easymock对builder进行了模拟,则可以抛出异常而不是返回值:

EasyMock.expect(builder.parse(myContent)).andThrow( myException);

其中myException是要抛出的异常实例(由新的MyException(...)创建);

编辑:示例测试代码:

@Test
public void parseThrowsIllegalStateException(){
    //... creating mock factory, builder and entity not shown

    //create new Exception to be thrown
    IllegalStateException expectedException = new IllegalStateException("expected");

    EasyMock.expect(mockBuilder.parse(mockContent).andThrow(expectedException);

    EasyMock.replay(...);

    //exercise your system under test which tries to parse the entity's Content
    //...
}

编辑2:既然您发布了实际测试代码,我认为问题可能就是这些问题:

EasyMock.expect(mockEntity.getContent()).andReturn(new ByteArrayInputStream(REPSONSE_EXAMPLE.getBytes()));

...
EasyMock.expect(builder.parse(new ByteArrayInputStream(malformed_XML.getBytes()))).andThrow(new SAXException("expected"));

我认为ByteArrayInputStream不会覆盖equals(),所以它使用的是Object.equals()。 ByteArrayInputStreams将不相等,因此EasyMock永远不会抛出异常

我会将builder.parse()期望更改为:

EasyMock.expect(builder.parse(EasyMock.isA(InputStream.class))).andThrow(new SAXException("expected"));

无论inputStream是什么,都会在调用parse时抛出。

作为旁注,您提到的错误消息“在记录状态下不允许调用验证”但我没有看到任何调用verify()或verifyAll()的地方。