Create a User / Group for UnitTest

Hello!

I’m trying to test my process with unit tests.

In the process I’m adding a candidate group to a task and send an email to the members of the group. To test this implementation I need to create a user and a group for the local unit test (h2 db).

My unit test looks like this:

public class ProcessUnitTest {

	private static Logger logger = LoggerFactory.getLogger(ProcessUnitTest.class);

	@ClassRule
	@Rule
	public static ProcessEngineRule rule = TestCoverageProcessEngineRuleBuilder.create().build();

	private static final String PROCESS_DEFINITION_KEY = "antragHA";

	static {
		LogFactory.useSlf4jLogging(); // MyBatis
	}

	@Before
	public void setup() {
		init(rule.getProcessEngine());
		
		
		IdentityService identityService = rule.getProcessEngine().getIdentityService();
		
		List <Group> groups = identityService.createGroupQuery().list();
		for(Group group: groups) {
			logger.debug(group.getId());
		}

		if (identityService.createGroupQuery().groupName("Mustergruppe").count() == 0) {
			Group group = identityService.newGroup("Mustergruppe");
			identityService.saveGroup(group);
		}

		if (identityService.createUserQuery().userId("MustermannM").count() == 0) {

			User user = identityService.newUser("MustermannM");
			user.setEmail("max.mustermann@abcdef.de");
			user.setFirstName("Max");
			user.setLastName("Mustermann");
			identityService.saveUser(user);

			identityService.createMembership(user.getId(), "Mustergruppe");
		}
	}

	/**
	 * Just tests if the process definition is deployable.
	 */
	@Test
	@Deployment(resources = "antragHA.bpmn")
	public void testParsingAndDeployment() {
		// nothing is done here, as we just want to check for exceptions during
		// deployment
	}
}

The following error occurs:

09:44:32.733 [main] ERROR org.camunda.bpm.engine.context - ENGINE-16004 Exception while closing command context: ENGINE-03083 Exception while executing Batch Database Operations with message '
### Error flushing statements.  Cause: org.apache.ibatis.executor.BatchExecutorException: org.camunda.bpm.engine.impl.persistence.entity.GroupEntity.insertGroup (batch index #1) failed. Cause: org.h2.jdbc.JdbcBatchUpdateException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
### Cause: org.apache.ibatis.executor.BatchExecutorException: org.camunda.bpm.engine.impl.persistence.entity.GroupEntity.insertGroup (batch index #1) failed. Cause: org.h2.jdbc.JdbcBatchUpdateException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
org.h2.jdbc.JdbcBatchUpdateException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
org.h2.jdbc.JdbcSQLException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
'. Flush summary: 
 [
  INSERT GroupEntity[Mustergruppe]
]
org.camunda.bpm.engine.ProcessEngineException: ENGINE-03083 Exception while executing Batch Database Operations with message '
### Error flushing statements.  Cause: org.apache.ibatis.executor.BatchExecutorException: org.camunda.bpm.engine.impl.persistence.entity.GroupEntity.insertGroup (batch index #1) failed. Cause: org.h2.jdbc.JdbcBatchUpdateException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
### Cause: org.apache.ibatis.executor.BatchExecutorException: org.camunda.bpm.engine.impl.persistence.entity.GroupEntity.insertGroup (batch index #1) failed. Cause: org.h2.jdbc.JdbcBatchUpdateException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
org.h2.jdbc.JdbcBatchUpdateException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
org.h2.jdbc.JdbcSQLException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
'. Flush summary: 
 [
  INSERT GroupEntity[Mustergruppe]
]
	at org.camunda.bpm.engine.impl.db.EnginePersistenceLogger.flushDbOperationsException(EnginePersistenceLogger.java:693) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.camunda.bpm.engine.impl.db.entitymanager.DbEntityManager.flushDbOperations(DbEntityManager.java:362) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.camunda.bpm.engine.impl.db.entitymanager.DbEntityManager.flushDbOperationManager(DbEntityManager.java:325) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.camunda.bpm.engine.impl.db.entitymanager.DbEntityManager.flush(DbEntityManager.java:297) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.camunda.bpm.engine.impl.interceptor.CommandContext.flushSessions(CommandContext.java:208) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.camunda.bpm.engine.impl.interceptor.CommandContext.close(CommandContext.java:137) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.camunda.bpm.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:116) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.camunda.bpm.engine.impl.interceptor.ProcessApplicationContextInterceptor.execute(ProcessApplicationContextInterceptor.java:70) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.camunda.bpm.engine.impl.interceptor.LogInterceptor.execute(LogInterceptor.java:33) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.camunda.bpm.engine.impl.IdentityServiceImpl.saveGroup(IdentityServiceImpl.java:104) ~[camunda-engine-7.11.0.jar:7.11.0]
	at de.nrw.lrh.ProcessUnitTest.setup(ProcessUnitTest.java:58) ~[test-classes/:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) ~[junit-4.12.jar:4.12]
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) ~[junit-4.12.jar:4.12]
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) ~[junit-4.12.jar:4.12]
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24) ~[junit-4.12.jar:4.12]
	at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55) ~[junit-4.12.jar:4.12]
	at org.camunda.bpm.engine.test.ProcessEngineRule$1.evaluate(ProcessEngineRule.java:170) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.junit.rules.RunRules.evaluate(RunRules.java:20) ~[junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) ~[junit-4.12.jar:4.12]
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) ~[junit-4.12.jar:4.12]
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) ~[junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) ~[junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) ~[junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) ~[junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) ~[junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) ~[junit-4.12.jar:4.12]
	at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55) ~[junit-4.12.jar:4.12]
	at org.camunda.bpm.engine.test.ProcessEngineRule$1.evaluate(ProcessEngineRule.java:170) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.junit.rules.RunRules.evaluate(RunRules.java:20) ~[junit-4.12.jar:4.12]
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363) ~[junit-4.12.jar:4.12]
	at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252) ~[na:na]
	at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141) ~[na:na]
	at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
	at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189) ~[surefire-api-2.12.4.jar:2.12.4]
	at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165) ~[surefire-booter-2.12.4.jar:2.12.4]
	at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85) ~[surefire-booter-2.12.4.jar:2.12.4]
	at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115) ~[surefire-booter-2.12.4.jar:2.12.4]
	at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75) ~[surefire-booter-2.12.4.jar:2.12.4]
Caused by: org.apache.ibatis.exceptions.PersistenceException: 
### Error flushing statements.  Cause: org.apache.ibatis.executor.BatchExecutorException: org.camunda.bpm.engine.impl.persistence.entity.GroupEntity.insertGroup (batch index #1) failed. Cause: org.h2.jdbc.JdbcBatchUpdateException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
### Cause: org.apache.ibatis.executor.BatchExecutorException: org.camunda.bpm.engine.impl.persistence.entity.GroupEntity.insertGroup (batch index #1) failed. Cause: org.h2.jdbc.JdbcBatchUpdateException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) ~[mybatis-3.4.4.jar:3.4.4]
	at org.apache.ibatis.session.defaults.DefaultSqlSession.flushStatements(DefaultSqlSession.java:255) ~[mybatis-3.4.4.jar:3.4.4]
	at org.camunda.bpm.engine.impl.db.sql.DbSqlSession.flushOperations(DbSqlSession.java:90) ~[camunda-engine-7.11.0.jar:7.11.0]
	at org.camunda.bpm.engine.impl.db.entitymanager.DbEntityManager.flushDbOperations(DbEntityManager.java:357) ~[camunda-engine-7.11.0.jar:7.11.0]
	... 44 common frames omitted
Caused by: org.apache.ibatis.executor.BatchExecutorException: org.camunda.bpm.engine.impl.persistence.entity.GroupEntity.insertGroup (batch index #1) failed. Cause: org.h2.jdbc.JdbcBatchUpdateException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
	at org.apache.ibatis.executor.BatchExecutor.doFlushStatements(BatchExecutor.java:146) ~[mybatis-3.4.4.jar:3.4.4]
	at org.apache.ibatis.executor.BaseExecutor.flushStatements(BaseExecutor.java:129) ~[mybatis-3.4.4.jar:3.4.4]
	at org.apache.ibatis.executor.BaseExecutor.flushStatements(BaseExecutor.java:122) ~[mybatis-3.4.4.jar:3.4.4]
	at org.apache.ibatis.executor.CachingExecutor.flushStatements(CachingExecutor.java:114) ~[mybatis-3.4.4.jar:3.4.4]
	at org.apache.ibatis.session.defaults.DefaultSqlSession.flushStatements(DefaultSqlSession.java:253) ~[mybatis-3.4.4.jar:3.4.4]
	... 46 common frames omitted
Caused by: org.h2.jdbc.JdbcBatchUpdateException: Eindeutiger Index oder Primärschlüssel verletzt: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"
Unique index or primary key violation: "PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES ('Mustergruppe', 1)"; SQL statement:
insert into ACT_ID_GROUP (ID_, NAME_, TYPE_, REV_)
    values (
      ?,
      ?,
      ?,
      1
    ) [23505-197]
	at org.h2.jdbc.JdbcPreparedStatement.executeBatch(JdbcPreparedStatement.java:1295) ~[h2-1.4.197.jar:1.4.197]
	at org.apache.ibatis.executor.BatchExecutor.doFlushStatements(BatchExecutor.java:122) ~[mybatis-3.4.4.jar:3.4.4]
	... 50 common frames omitted

(shortened)

The new group is not already there because identityService.createGroupQuery().groupName(“Mustergruppe”).count() returns zero but I can’t create a new group because it’s already there?

So my question is: how do I create a user and group in the process engine for my local unit test. The unit test is working fine without trying to create a user / group and the process is working fine in my tomcat/mysqldb environment after deployment.

Hi, this works here:

package processtest;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.identity.Group;
import org.camunda.bpm.engine.identity.User;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.extension.process_test_coverage.junit.rules.TestCoverageProcessEngineRuleBuilder;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import java.util.List;

import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareTests.identityService;
import static org.junit.Assert.assertEquals;

@Slf4j
@Deployment(resources = {"loan-process.bpmn"})
public class ProcessUnitTest {

    public static final String EXAMPLEGROUP = "Mustergruppe";
    public static final String EXAMPLEUSER = "MustermannM";
    @ClassRule
    @Rule
    public static ProcessEngineRule rule = TestCoverageProcessEngineRuleBuilder.create().build();

    @Before
    public void setup() {
        IdentityService identityService = identityService();

        for (Group group : identityService.createGroupQuery().list()) log.info(group.getId());

        if (identityService.createGroupQuery().groupName(EXAMPLEGROUP).count() == 0) {
            Group group = identityService.newGroup(EXAMPLEGROUP);
            identityService.saveGroup(group);
        }

        if (identityService.createUserQuery().userId(EXAMPLEUSER).count() == 0) {
            User user = identityService.newUser(EXAMPLEUSER);
            user.setEmail("max.mustermann@abcdef.de");
            user.setFirstName("Max");
            user.setLastName("Mustermann");
            identityService.saveUser(user);
            identityService.createMembership(user.getId(), EXAMPLEGROUP);
        }
    }

    @Test
    public void someTest() {
        List <Group> groups = identityService().createGroupQuery().list();
        assertEquals(groups.size(),1);
        assertEquals(groups.get(0).getId(), EXAMPLEGROUP);

        List <User> users = identityService().createUserQuery().userId(EXAMPLEUSER).memberOfGroup(EXAMPLEGROUP).list();
        assertEquals(users.size(),1);
        assertEquals(users.get(0).getId(), EXAMPLEUSER);
    }
}

Camunda.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--    <bean id="processEngineConfiguration" class="org.camunda.bpm.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">-->

    <bean id="processEngineConfiguration"
          class="org.camunda.bpm.extension.process_test_coverage.junit.rules.ProcessCoverageInMemProcessEngineConfiguration">
        <property name="history" value="full"/>
        <property name="expressionManager">
            <bean class="org.camunda.bpm.engine.test.mock.MockExpressionManager"/>
        </property>
        <property name="processEnginePlugins">
            <list>
<!--                <bean class="org.camunda.feel.CamundaFeelEnginePlugin"/>-->
            </list>
        </property>
    </bean>
</beans>
1 Like

Thank you!