2014-01-17 125 views
0

想知道如何爲以下代碼編寫UT代碼嗎?想知道如何爲以下代碼編寫UT代碼嗎?

public Set<OMEntity> applyInitialDump(Map<Class<? extends Entity>, List<Entity>> centralModelRelated) { 

    try { 
     return _executionUnit.executeSynch(new ApplyInitialDumpOnCentralModel(_context, centralModelRelated)); 
    } catch (ExecutionException e) { 
     throw new RuntimeException(e); 
    } 
} 

我嘗試嘲笑_executionUnit,但如何嘲笑參數(ApplyInitialDumpOnCentralModel)?謝謝。

附上一些測試代碼供參考。

 Map<Class<? extends Entity>,List<Entity>> centralModelRelated = new HashMap<Class<? extends Entity>, List<Entity>>(); 
    CentralModelUnitOfWork unitOfWork = new ApplyInitialDumpOnCentralModel(omContext, centralModelRelated); 
    executionUnit = EasyMock.createMock(ExecutionUnit.class); 
    EasyMock.expect(executionUnit.executeSynch(??????????)).andReturn(new Object()).once();; 
    EasyMock.replay(executionUnit); 

    centralModel.applyInitialDump(centralModelRelated); 

回答

1

不幸的是,因爲該ApplyInitialDumpOnCentralModel對象在方法中實例化,所以不可能嘲笑該對象本身。

但是,executeSynch的呼叫仍然可以使用EasyMock's Capture類來模擬。

所以你的測試最終會看起來像這樣:

Map<Class<? extends Entity>,List<Entity>> centralModelRelated = new HashMap<Class<? extends Entity>, List<Entity>>(); 
Capture<ApplyInitialDumpOnCentralModel> captureObject = new Capture<ApplyInitialDumpOnCentralModel>(); 

executionUnit = EasyMock.createMock(ExecutionUnit.class); 
EasyMock.expect(executionUnit.executeSynch(EasyMock.capture(captureObject))).andReturn(new Object()).once();; 
EasyMock.replay(executionUnit); 

centralModel.applyInitialDump(centralModelRelated); 

EasyMock.verify(executionUnit); //Don't forget to verify your mocks :) 

CentralModelUnitOfWork expectedUnitOfWork = new ApplyInitialDumpOnCentralModel(omContext, centralModelRelated); 
ApplyInitialDumpOnCentralModel actualUnitOfWork = captureObject.getValue(); 
//Then whatever assertion you want to make about the expected and actual unit of work.