我可以在单元测试中检查,某些方法被调用2次吗?如何?



我有bpmn项目,使用Camunda。

我有一个委托类,它检查具有相同旅程代码和状态的进程是否存在:

@Component
public class CheckIsDuplicateDepartedJourneyProcessedDelegate implements JavaDelegate {
@Override
public void execute(DelegateExecution execution) throws Exception {
String currentProcessInstanceId = execution.getProcessInstanceId();
String journeyCode = DelegateExecutionUtils.getStringVariable(execution, JOURNEY_CODE);
String journeyStatus = DelegateExecutionUtils.getStringVariable(execution, TRIP_STATUS);
boolean hasDuplicate =
execution
.getProcessEngine()
.getRuntimeService()
.createProcessInstanceQuery()
.processDefinitionKey(UPDATE_JOURNEY_STATUS_PROCESS_ID)
.processInstanceBusinessKey(journeyCode)
.variableValueEquals(TRIP_STATUS, journeyStatus)
.list()
.stream()
.anyMatch(process -> !process.getProcessInstanceId().equals(currentProcessInstanceId));
execution.setVariable(DUPLICATE_PROCESS, hasDuplicate);
}
}

我如何在单元测试中检查,该方法execute(…)或execute . getprocessinstanceid()被调用2次(每2个进程中1次)?我需要检查两个进程是否工作,并且想要跟踪委派中提到的一些方法是否每个进程调用一次(2个进程中有2个)。

我当前的单元测试。它工作不好,因为它说,方法execute(…)没有被调用。

public class UpdateJourneyStatusProcessTest extends BaseTest {
@Spy private CheckIsDuplicateDepartedJourneyProcessedDelegate checkDelegate = new CheckIsDuplicateDepartedJourneyProcessedDelegate();
...
// when
sender.send(firstCommand); // recieving this command initiates process and delegate work
sender.send(secondCommand);
// then
verify(checkDelegate, times(2)).execute(any(DelegateExecution.class)); // says that method was called 0 times
...
}
}

谢谢你的帮助。

我认为最好的方法是设置一个进程,并检查没有设置DUPLICATE_PROCESS。

然后设置一个额外的(重复的)进程,调用你的方法,然后检查你的DUPLICATE_PROCESS是否设置。

我不确定我是否理解了所有的细节,但我假设你可以通过直接调用命令来启动这些过程。

您发布的代码是不完整的,所以我不确定这一工作的一个重要步骤是否完成。也许这就是问题所在。

检查execute(...)是否被调用-sender对象应该有模拟对象-checkDelegate

要检查execution.getProcessInstanceId()是否被调用-您应该创建DelegateExecution execution的模拟并将其设置在checkDelegate对象中。

你可以通过构造函数传递它,也可以在UnitTest初始化后设置它。

您运行的是普通Java测试还是Spring测试?

流程引擎将按照您在流程模型中指定的方式解析委托。如果你的处理模型引用了一个Java类,那么无论如何它都会实例化这个类。如果使用Delegate表达式,则按名称引用Spring bean。由于您在测试中实例化了CheckIsDuplicateDepartedJourneyProcessedDelegate,所以我假设它不是Spring测试,而是普通的Java测试。在普通Java测试中,您必须确保Camunda能够解析bean名称。这是使用mock .register(…)完成的。您是否在流程模型中的Delegate表达式中的bean名称下注册了@spy bean ?

我不会使用一个委托,而是一个表达式,然后不检查委托级别,但检查两个进程实例是否遵循期望的路径使用正常断言,例如assertThat(pi).hasPassed("somewhere").isWaitingAt("someTask");

下面是一个示例模型,其中包含一个表达式,可用于实现单例行为。您可以按照委托实现中所示的行调整表达式。

https://github.com/rob2universe/process-models/blob/798c2097fffc330be7dc498f0354b02dc32410c6/bpmn/singleton.bpmn课时

最新更新