2

我有一个父工作流(ParentWorkflow)调用一个子工作流(ChildWorkflow),我正在尝试测试这个调用。

父代码如下所示:

public class ParentWorkflow {
    private final ChildWorkflowClientFactory childWorkflowClientFactory =
            new ChildWorkflowClientFactoryImpl();

    public void runWorkflow() {
        new TryCatch() {
            @Override
            protected void doTry() throws Throwable {
                Promise<Void> workflowFinished = childWorkflowClient.childWorkflow(x);
                ...
            }
        ...
    }
}

我想模拟 childWorkflowClient.childWorkflow(x) 调用,但是当我连接单元测试时,我似乎没有注入客户端工厂的选项,单元测试代码如下所示:

@Rule
public WorkflowTest workflowTest = new WorkflowTest();
@Mock
private Activities mockActivities;

private ParentWorkflowClientFactory workflowFactory
        = new ParentWorkflowClientFactoryImpl();

@Before
public void setUp() throws Exception {
    // set up mocks
    initMocks(this);

    workflowTest.addActivitiesImplementation(mockActivities);
    workflowTest.addWorkflowImplementationType(ParentWorkflowImpl.class);
    workflowTest.addWorkflowImplementationType(ChildWorkflowImpl.class);

我似乎无法将任何东西传递给工作流实现类,还有其他方法可以模拟子工作流吗?

4

2 回答 2

6

您可以在不使用workflowTest的情况下直接模拟其依赖项来测试工作流代码:

/**
 * Rule is still needed to initialize asynchronous framework.
 */
@Rule
public WorkflowTest workflowTest = new WorkflowTest();
@Mock
private ActivitiesClient mockActivities;
@Mock
private BWorkflowClientFactory workflowFactory;


@Before
public void setUp() throws Exception {
  // set up mocks
  initMocks(this);
}

@Test
public void myTest() {
  AWorkflowImpl w = new AWorkflowImpl(workflowFactory);
  w.execute(); // whatever execute method of the workflow
}

这种方法允许测试封装在其他对象中的部分工作流,而不是整个工作流。

如果出于某种原因(例如,您使用的是除 JUnit 之外的其他测试框架)您不想依赖 WorkflowTest @Rule 异步代码,则始终可以使用AsyncScope执行:

@Test
public void asyncTest() {
   AsyncScope scope = new AsyncScope() {
      protected void doAsync() {
         // Any asynchronous code
         AWorkflowImpl w = new AWorkflowImpl(workflowFactory);
         w.execute(); // whatever execute method of the workflow
      }
   };
   scope.eventLoop();
}
于 2015-05-28T00:05:48.213 回答
0

编辑:以下仅适用于 SpringWorkflowTest;WorkflowTestaddWorkflowImplementation由于某种原因没有。

使用 WorkflowTest 的正确方法是为子工作流添加一个模拟实现,而不是添加实际类型:

@Rule
public SpringWorkflowTest workflowTest = new SpringWorkflowTest();
@Mock
private Activities mockActivities;
@Mock
private ChildWorkflow childWorkflowMock;

private ParentWorkflowClientFactory workflowFactory
        = new ParentWorkflowClientFactoryImpl();

@Before
public void setUp() throws Exception {
    // set up mocks
    initMocks(this);

    workflowTest.addActivitiesImplementation(mockActivities);
    workflowTest.addWorkflowImplementationType(ParentWorkflowImpl.class);
    workflowTest.addWorkflowImplementation(childWorkflowMock);
    ...
}

然后,当您使用工厂时,框架将调用这个模拟而不是实际的实现。

于 2018-05-10T16:24:25.167 回答