java - 知道如何为下面的代码编写 UT 吗?

标签 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);

最佳答案

遗憾的是,由于 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.

关于java - 知道如何为下面的代码编写 UT 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21179958/

相关文章:

java - 使用 PowerMockito 模拟私有(private)方法

java - 如何将此更改日志库添加到 Eclipse 中当前的 Android 项目中?

java - 二叉树插入根始终为空

ant - JUnit Ant任务报告可以忽略测试吗?

java - 等价于 EasyMock 中的 LastCall.IgnoreArguments

java - Junit,Mockito,如何测试回调

java - 使用 PowerMock 模拟静态和动态方法

java - 列出来自 Android App 的包中的文件返回 null

java - IText如何调整pdf页面

linux - Linux 中的 Eclipse : running a Junit coverage test gives an error "permission denied"