我正在测试此代码:
/**
* Construct confluence object
*/
public Confluence(XWikiXmlRpcClient rpcConfluence1, XWikiXmlRpcClient rpcConfluence2) {
this.rpcConfluence1 = rpcConfluence1;
this.rpcConfluence2 = rpcConfluence2;
}
/**
* Method to publish new confluence page to Confluence
*
* @throws IOException
*/
public void publishNew() throws IOException {
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);
}
}
使用Mockito:
@BeforeTest
public void setup() {
confluence1 = Mockito.mock(XWikiXmlRpcClient.class);
confluence2 = Mockito.mock(XWikiXmlRpcClient.class);
publish = new Confluence(confluence1, confluence2);
}
@Test
public void testAddPage() {
try {
publish.publishNew();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
问题在于:
Page page = new Page();
尝试时:
newPage.getUrl();
我得到一个空指针异常,因为这个对象是在模拟框架之外创建的,我无法找到一种方法来模拟它。赞赏的想法:)
答案 0 :(得分:4)
在模拟对象上调用方法时,除非另行指定,否则将获得null
结果。您必须指定方法rpcConfluence1.storePage(page);
应返回的内容而不是null
。了解Mockito.when
方法。
首先尝试在@BeforeTest方法中进行设置,如下所示
@BeforeTest
public void setup() {
confluence1 = Mockito.mock(XWikiXmlRpcClient.class);
Page testPage = new Page();
when(confluence1.storePage(any(Page.class))).thenReturn(testPage);
confluence2 = Mockito.mock(XWikiXmlRpcClient.class);
publish = new Confluence(confluence1, confluence2);
}