Is any idea how to write UT for below code?

    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);
    }
}

I try to mock _executionUnit, but how to mock the parameter(ApplyInitialDumpOnCentralModel) ? Thanks.

Attache some test code for reference.

        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);
有帮助吗?

解决方案

Sadly, because the ApplyInitialDumpOnCentralModel object is instantiated within the method, it is not possible to mock that object itself.

However, the call to executeSynch can still be mocked using EasyMock's Capture class.

So your test would end up looking something like this:

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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top