为什么Mockito不会抛出异常?

时间:2015-11-19 10:39:45

标签: java testng mockito

我有这个测试,测试异常处理:

@BeforeTest
public void setup() throws XmlRpcException {
confluence1 = Mockito.mock(XWikiXmlRpcClient.class);
confluence2 = Mockito.mock(XWikiXmlRpcClient.class);
XWikiPage testPage = new XWikiPage();
testPage.setContent("Test");
testPage.setTitle("Page Title");
testPage.setUrl("http://confluence:8080/Test");
Mockito.when(confluence1.storePage(Mockito.any(Page.class))).thenReturn(testPage);
Mockito.when(confluence2.getPage(Mockito.anyString())).thenReturn(testPage);
publish = new Confluence(confluence1, confluence2); 
}


@Test(expectedExceptions = XmlRpcException.class)
public void testAddPageException() throws XmlRpcException {
    Mockito.doThrow(new XmlRpcException("Error")).when(confluence1).
                            login(Mockito.anyString(), Mockito.anyString());
    publish.publishNew();

}

测试此代码:

public void publishNew() throws XmlRpcException {
    DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    Date today = Calendar.getInstance().getTime(); 

    try {
        if (parentPageId == null) {
            LOGGER.error("Unable to publish to confluence - required page id of parent confluence page is not set");
        }
        LOGGER.info("Logging in to Confluence");
        rpcConfluence1.login(userName, passWord);
        Page page = new Page();                    
        page.setSpace(owrConf.getString(ConfigKeys.CONFLUENCE_SPACE));
        page.setTitle(owrConf.getString(ConfigKeys.CONFLUENCE_NEW_PAGE_TITLE) + "_" + df.format(today));
        LOGGER.info("Adding new page: " + page.getTitle() + " to space " + page.getSpace());            
        page.setContent(reformatMarkup());
        page.setParentId(parentPageId);            
        Page newPage = rpcConfluence1.storePage(page);          
        LOGGER.info("New page: " + newPage.getUrl());
        savePageUrl(newPage);
        } catch (XmlRpcException e) {
            LOGGER.error("Error publishing to confluence", e);
        }

}

在publishNew()中调用login方法时,应该抛出XmlRpcException。相反,我得到一个错误:

Method PublishTest.testAddPageException()[pri:0, instance:com.report.publish.PublishTest@6b4886d3] should have thrown an exception of class org.apache.xmlrpc.XmlRpcException

我无法弄清楚它为什么不起作用。

1 个答案:

答案 0 :(得分:3)

您正在抓取publishNew ... } catch (XmlRpcException e) { LOGGER.error("Error publishing to confluence", e); }中的异常。因为测试失败。