3
我在一個傳統的項目,使用EasyMock沒有選項,包括Mockito,說我一直無法獲得一個單元測試與PowerMockRule一起工作。我發現幾乎所有關於如何利用該規則的例子都是用Mockito進行的。我真的可以用EasyMock來解決這個問題。PowerMockRule與EasyMock NOT Moquito
@RunWith(UnitilsJUnit4TestClassRunner.class)
public class ModuleCloningServiceImplTest {
@Rule
public PowerMockRule rule = new PowerMockRule();
//...
@Test
public void copyModuleToPages_success_customLayoutTileCopy_default_tile() {
ModuleType moduleType = getModuleType(ModuleTypeCode.COUPON, 2, 3);
Module<CouponViewer> module = getModule(1L, moduleType);
Page copyPage = getPage(1L, moduleType);
PageLayout newPageLayout = DomainObjectBuilder.newPageLayout().build();
newPageLayout.setCode(PageLayoutCode.CUSTOM);
copyPage.setPageLayout(newPageLayout);
List<Page> pages = Arrays.asList(copyPage);
PowerMock.mockStatic(CustomPageLayoutUtils.class);
CustomPageLayoutUtils.tileNumberExistsInCustomPageLayout(9, null);
expectLastCall().andReturn(false);
CustomPageLayoutUtils.getPreferredOrDefaultTile(copyPage, moduleType);
expectLastCall().once().andReturn(2);
PowerMock.replayAll();
OperationReport operationReport = moduleCloningService.copyModuleToPages(module, pages, 9);
PowerMock.verifyAll();
checkCopySuccessInPages(pages);
for (Page page : pages) {
for (ModulePage<? extends JaxbModule> modulePage : page.getModulePages()) {
Assert.assertEquals(Integer.valueOf(2), modulePage.getTileNumber());
}
}
Assert.assertTrue(operationReport.isSuccesful());
}
到CustompPageLayoutUtils每個呼叫進入該方法,而不是使用模擬。我已經在這段代碼上嘗試了一些permuations,但這是我的最後一次嘗試。任何見解都將非常受歡迎。我希望還有其他人可以利用這個問題的解決方案。
對PowerMock不太瞭解,但這是否與缺少'@ PrepareForTest'有關? –
另外[this page](https://code.google.com/p/powermock/wiki/PowerMockRule)似乎聲稱當你使用'@ Rule'註釋時你不需要'@ RunWith' .. ... –
事實上,如果我從零開始編寫測試,我不需要它。然而,這是一個需要擴展的傳統測試。如果我刪除runswith ...以及一切都失敗了,所以我需要保持它。因此我需要Rule。如果我用PowerMockRunner運行,我可以讓我的測試工作,但其他測試失敗。最實用的方法是隻編寫另一個測試類並使用PowerMockRunner運行。但這真是太難看了,我喜歡正確地做,而不是採用解決方法。我會調查PrepareForTest,但我真誠地懷疑這是否會,儘管如此。 – kenny