有没有想过如何为下面的代码编写UT?

时间:2014-01-17 07:14:22

标签: java junit easymock

有没有想过如何为下面的代码编写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 个答案:

答案 0 :(得分:1)

可悲的是,因为ApplyInitialDumpOnCentralModel对象在方法中被实例化,所以不可能自己模拟该对象。

但是,仍然可以使用EasyMock's Capture类来模拟对executeSynch的调用。

所以你的测试最终会看起来像这样:

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.