【问题标题】:How to skip invoking another method to create a mock object?如何跳过调用另一个方法来创建模拟对象?
【发布时间】:2020-07-01 16:39:28
【问题描述】:

我有一个方法类,如果我想测试一个方法,但是这个方法中创建的对象依赖于类中的其他方法。我不想实际调用其他方法,我只想创建模拟对象进行测试。我该怎么做?

@Test
public void testLoadException(String id) {

    WorkflowExecution mockWorkflowExection = getWorkflowExecution(id);

}

我试着这样做

WorkflowExecution mockExecution = EasyMock.create(WorkflowExecution.class);
Easy.expect(this.test.getWorkflowExecution(EasyMock.anyString())).andReturn(mockExecution);

但这不起作用,测试给了我Nullpointer exception。 那我可以跳过getWorkflowExecution(id)的电话吗,谢谢!

【问题讨论】:

    标签: easymock


    【解决方案1】:

    您需要一个部分模拟。你的例子没有多大意义。所以这就是你想要的。

    public class WorkflowExecution {
        public void theRealMethodIWantToCall() {
            theMethodIWantToMock();
        }
    
        void theMethodIWantToMock() {
    
        }
    }
    
    @Test
    public void testLoadException() {
        WorkflowExecution execution = partialMockBuilder(WorkflowExecution.class)
                .addMockedMethod("theMethodIWantToMock")
                .mock();
        execution.theMethodIWantToMock();
        replay(execution);
    
        execution.theRealMethodIWantToCall();
    
        verify(execution);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多