You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot项目中配置Camunda单元测试环境

问题根因

你手动调用createStandaloneInMemProcessEngineConfiguration()实例化ProcessEngine的方式完全绕过了Spring Boot的自动配置流程,所有基于Spring上下文加载的配置文件、参数绑定、Bean注入逻辑都不会生效,自然无法读取application-test.yml中的配置项,也无法复用原有业务代码的依赖注入逻辑。

正确解决方案

第一步:补充测试依赖

在pom.xml中添加Camunda Spring Boot测试依赖和H2内存数据库依赖:

<dependency>
    <groupId>org.camunda.bpm.springboot</groupId>
    <artifactId>camunda-bpm-spring-boot-starter-test</artifactId>
    <version>7.15.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

第二步:编写标准Spring Boot测试类

直接使用@SpringBootTest注解加载Spring上下文,Camunda相关服务直接通过@Autowired注入即可,不需要手动创建ProcessEngine,Spring Boot自动配置会自动读取所有生效Profile的配置文件,包括application-test.yml中的参数:

@SpringBootTest
@ActiveProfiles("test")
// 可选:自动部署你的BPMN文件,填写项目中BPMN文件的类路径即可
@Deployment(resources = "path/to/your/process.bpmn")
public class EntitlementServiceTest {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IdentityService identityService;

    // 其他业务Bean如果需要mock,用@MockBean注解
    @MockBean
    private YourBusinessService yourBusinessService;

    @Test
    public void testProcessFlow() {
        // 直接使用注入的服务编写测试逻辑即可
        // 比如启动流程:runtimeService.startProcessInstanceByKey("processKey");
    }
}

第三步:配置application-test.yml

在src/test/resources下新建application-test.yml,按需要配置测试环境参数即可,格式和主配置完全一致,会自动覆盖主配置的同名字段:

# 测试用H2内存数据库配置
spring.datasource:
  url: jdbc:h2:mem:camunda-test;DB_CLOSE_ON_EXIT=FALSE
  username: sa
  password:
  driver-class-name: org.h2.Driver

# 自定义Camunda参数,会自动生效
camunda.bpm:
  generic-properties:
    properties:
      generalResourceWhitelistPattern: "[a-zA-Z0-9,'_\\$\\-\\.\\+\\!\\*\\(\\)]+|camunda-admin"
  # 测试环境可以自定义admin用户,加快启动速度
  admin-user:
    id: test
    password: test

注意事项

  • 确保你的Spring Boot版本和Camunda 7.15兼容,Camunda 7.15支持Spring Boot 2.4.x/2.5.x版本,避免版本冲突导致自动配置失效。
  • 如果不需要启动完整的Spring上下文,可使用@CamundaSpringBootTest注解替换@SpringBootTest,仅加载Camunda相关的Bean,加快测试启动速度。

内容的提问来源于stack exchange,提问作者user3573403

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:24:03