├── .editorconfig ├── .github ├── dependabot.yml ├── release-notes.yml └── workflows │ ├── build.yml │ ├── deploy.yml │ ├── release-notes.yml │ └── toc.yml ├── .gitignore ├── .mvn └── wrapper │ └── maven-wrapper.properties ├── .tool-versions ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml ├── renovate.json └── src ├── main └── java │ └── org │ └── camunda │ └── community │ └── mockito │ ├── CamundaMockito.java │ ├── DelegateExpressions.java │ ├── Expressions.java │ ├── ProcessExpressions.java │ ├── QueryMocks.java │ ├── ServiceExpressions.java │ ├── answer │ ├── AbstractAnswer.java │ ├── ExecutionListenerAnswer.java │ ├── FluentAnswer.java │ ├── FluentMessageCorrelationBuilderAnswer.java │ ├── JavaDelegateAnswer.java │ └── TaskListenerAnswer.java │ ├── cases │ ├── CaseExecutionEntityFake.java │ ├── CaseExecutionFake.java │ ├── CaseInstanceFake.java │ └── CaseInstanceFakeBuilder.java │ ├── delegate │ ├── DelegateCaseExecutionFake.java │ ├── DelegateCaseVariableInstanceFake.java │ ├── DelegateExecutionFake.java │ ├── DelegateFake.java │ ├── DelegateTaskFake.java │ ├── IncidentFake.java │ ├── ProcessEngineServicesAwareFake.java │ └── VariableScopeFake.java │ ├── function │ ├── CreateInstance.java │ ├── DeployProcess.java │ ├── GetProcessEngineConfiguration.java │ ├── NameForType.java │ ├── NodeToString.java │ ├── ParseDelegateExpressions.java │ └── ReadXmlDocumentFromResource.java │ ├── message │ └── MessageCorrelationBuilderMock.java │ ├── mock │ ├── FluentExecutionListenerMock.java │ ├── FluentJavaDelegateMock.java │ ├── FluentMock.java │ └── FluentTaskListenerMock.java │ ├── process │ ├── CallActivityMock.java │ ├── CallActivityMockForSpringContext.java │ ├── ProcessDefinitionFake.java │ └── ProcessInstanceFake.java │ ├── query │ ├── AbstractQueryMock.java │ ├── ActivityStatisticsQueryMock.java │ ├── AuthorizationQueryMock.java │ ├── BatchQueryMock.java │ ├── BatchStatisticsQueryMock.java │ ├── CaseDefinitionQueryMock.java │ ├── CaseExecutionQueryMock.java │ ├── CaseInstanceQueryMock.java │ ├── DecisionDefinitionQueryMock.java │ ├── DeploymentQueryMock.java │ ├── DeploymentStatisticsQueryMock.java │ ├── EventSubscriptionQueryMock.java │ ├── ExecutionQueryMock.java │ ├── ExternalTaskQueryMock.java │ ├── FilterQueryMock.java │ ├── GroupQueryMock.java │ ├── HistoricActivityInstanceQueryMock.java │ ├── HistoricActivityStatisticsQueryMock.java │ ├── HistoricBatchQueryMock.java │ ├── HistoricCaseActivityInstanceQueryMock.java │ ├── HistoricCaseInstanceQueryMock.java │ ├── HistoricDecisionInstanceQueryMock.java │ ├── HistoricDetailQueryMock.java │ ├── HistoricIdentityLinkLogQueryMock.java │ ├── HistoricIncidentQueryMock.java │ ├── HistoricJobLogQueryMock.java │ ├── HistoricProcessInstanceQueryMock.java │ ├── HistoricTaskInstanceQueryMock.java │ ├── HistoricVariableInstanceQueryMock.java │ ├── IncidentQueryMock.java │ ├── JobDefinitionQueryMock.java │ ├── JobQueryMock.java │ ├── ProcessDefinitionQueryMock.java │ ├── ProcessDefinitionStatisticsQueryMock.java │ ├── ProcessInstanceQueryMock.java │ ├── TaskQueryMock.java │ ├── TenantQueryMock.java │ ├── UserOperationLogQueryMock.java │ ├── UserQueryMock.java │ └── VariableInstanceQueryMock.java │ ├── service │ ├── CaseServiceStubBuilder.java │ ├── RuntimeServiceFluentMock.java │ ├── RuntimeServiceStubBuilder.java │ └── TaskServiceStubBuilder.java │ ├── task │ ├── LockedExternalTaskFake.java │ └── TaskFake.java │ ├── typedvalues │ └── VariableContextFake.java │ └── verify │ ├── AbstractMockitoVerification.java │ ├── CaseServiceVerification.java │ ├── ExecutionListenerVerification.java │ ├── JavaDelegateVerification.java │ ├── MockitoVerification.java │ ├── RuntimeServiceVerification.java │ ├── TaskListenerVerification.java │ └── TaskServiceVerification.java └── test ├── java └── org │ └── camunda │ └── community │ └── mockito │ ├── AutoMockProcessTest.java │ ├── CallActivityMockBindingDeploymentTest.java │ ├── CallActivityMockExampleTest.java │ ├── ManualMockProcessTest.java │ ├── MessageCorrelationMockExample.java │ ├── MostUsefulProcessEngineConfiguration.java │ ├── QueryMocksExample.java │ ├── answer │ ├── AbstractAnswerTest.java │ └── FluentAnswerTest.java │ ├── cases │ ├── CaseExecutionFakeTest.java │ └── CaseInstanceFakeTest.java │ ├── delegate │ ├── DelegateCaseExecutionFakeTest.java │ ├── DelegateCaseVariableInstanceFakeTest.java │ ├── DelegateExecutionFakeTest.java │ ├── DelegateTaskFakeTest.java │ ├── ProcessEngineServicesAwareFakeTest.java │ └── VariableScopeFakeTest.java │ ├── function │ ├── NameForExpressionTypeTest.java │ ├── ParseDelegateExpressionsTest.java │ └── ReadXmlDocumentFromResourceTest.java │ ├── mock │ ├── FluentExecutionListenerMockTest.java │ ├── FluentJavaDelegateMockTest.java │ ├── FluentMockTest.java │ └── FluentTaskListenerMockTest.java │ ├── process │ ├── ProcessDefinitionFakeTest.java │ └── ProcessInstanceFakeTest.java │ ├── query │ ├── AuthorizationQueryMockTest.java │ ├── ProcessInstanceQueryMockTest.java │ └── TaskQueryMockTest.java │ ├── service │ ├── CaseServiceStubbingTest.java │ ├── CaseServiceVerifierTest.java │ ├── RuntimeServiceFluentMockTest.java │ ├── RuntimeServiceStubbingTest.java │ ├── RuntimeServiceVerifierTest.java │ ├── TaskServiceStubbingTest.java │ └── TaskServiceVerifierTest.java │ ├── spring │ └── SpringListeners.java │ ├── task │ └── LockedExternalTaskFakeTest.java │ ├── typedvalues │ └── VariableContextFakeTest.java │ └── verify │ └── MockitoVerificationTest.java └── resources ├── MockProcess.bpmn ├── MockProcess_withoutNS.bpmn ├── process_with_callActivity_binding_deployment.bpmn └── simplelogger.properties /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | # Change these settings to your own preference 10 | indent_style = space 11 | indent_size = 2 12 | 13 | # We recommend you to keep these unchanged 14 | end_of_line = lf 15 | insert_final_newline = true 16 | charset = utf-8 17 | trim_trailing_whitespace = true 18 | max_line_length = 140 19 | 20 | [*.md] 21 | trim_trailing_whitespace = false 22 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: maven 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | -------------------------------------------------------------------------------- /.github/release-notes.yml: -------------------------------------------------------------------------------- 1 | changelog: 2 | sections: 3 | - title: ":rocket: Enhancements & Features" 4 | labels: [ "enhancement" ] 5 | - title: ":bug: Bug Fixes" 6 | labels: [ "bug" ] 7 | - title: ":hammer_and_wrench: Chore" 8 | labels: [ "dependencies", "build" ] 9 | issues: 10 | exclude: 11 | labels: [ "duplicate", "question" ] 12 | contributors: 13 | exclude: 14 | names: [ "dependabot[bot]", "codacy-badger" ] 15 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build project with Maven 2 | on: 3 | pull_request: 4 | push: 5 | branches-ignore: [master] 6 | schedule: 7 | - cron: '2 2 * * 1' # run nightly master builds every monday 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v4 15 | - name: Java setup 16 | uses: actions/setup-java@v4 17 | with: 18 | java-version: 17 19 | distribution: zulu 20 | cache: maven 21 | - name: Run Maven 22 | run: ./mvnw -B clean install com.mycila:license-maven-plugin:check 23 | - name: Run CodeCov 24 | uses: codecov/codecov-action@v5 25 | 26 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy artifacts with Maven 2 | on: 3 | push: 4 | branches: [master] 5 | release: 6 | types: [published] 7 | jobs: 8 | publish: 9 | runs-on: ubuntu-24.04 10 | steps: 11 | - uses: actions/checkout@v4 12 | - name: Set up Java environment 13 | uses: actions/setup-java@v4 14 | with: 15 | java-version: 17 16 | distribution: zulu 17 | cache: maven 18 | gpg-private-key: ${{ secrets.MAVEN_CENTRAL_GPG_SIGNING_KEY_SEC }} 19 | gpg-passphrase: MAVEN_CENTRAL_GPG_PASSPHRASE 20 | 21 | - name: Deploy SNAPSHOT / Release 22 | uses: camunda-community-hub/community-action-maven-release@v1.2.3 23 | with: 24 | release-version: ${{ github.event.release.tag_name }} 25 | release-profile: community-action-maven-release 26 | nexus-usr: ${{ secrets.NEXUS_USR }} 27 | nexus-psw: ${{ secrets.NEXUS_PSW }} 28 | maven-usr: ${{ secrets.COMMUNITY_HUB_MAVEN_CENTRAL_OSS_USR }} 29 | maven-psw: ${{ secrets.COMMUNITY_HUB_MAVEN_CENTRAL_OSS_PSW }} 30 | maven-url: oss.sonatype.org 31 | maven-auto-release-after-close: true 32 | maven-gpg-passphrase: ${{ secrets.MAVEN_CENTRAL_GPG_SIGNING_KEY_PASSPHRASE }} 33 | github-token: ${{ secrets.GITHUB_TOKEN }} 34 | id: release 35 | 36 | - if: github.event.release 37 | name: Attach artifacts to GitHub Release (Release only) 38 | uses: actions/upload-release-asset@v1 39 | env: 40 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 41 | with: 42 | upload_url: ${{ github.event.release.upload_url }} 43 | asset_path: ${{ steps.release.outputs.artifacts_archive_path }} 44 | asset_name: ${{ steps.release.outputs.artifacts_archive_path }} 45 | asset_content_type: application/zip 46 | 47 | - name: Run CodeCov 48 | uses: codecov/codecov-action@v5 49 | -------------------------------------------------------------------------------- /.github/workflows/release-notes.yml: -------------------------------------------------------------------------------- 1 | # Trigger the workflow on milestone events 2 | on: 3 | milestone: 4 | types: [closed] 5 | name: Milestone Closure 6 | jobs: 7 | create-release-notes: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout code 11 | uses: actions/checkout@master 12 | 13 | - name: Create Release Notes Markdown 14 | uses: docker://decathlon/release-notes-generator-action:3.1.5 15 | env: 16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token 17 | OUTPUT_FOLDER: temp_release_notes 18 | USE_MILESTONE_TITLE: "true" 19 | 20 | - name: Get the name of the created Release Notes file and extract Version 21 | run: | 22 | RELEASE_NOTES_FILE=$(ls temp_release_notes/*.md | head -n 1) 23 | echo "RELEASE_NOTES_FILE=$RELEASE_NOTES_FILE" >> $GITHUB_ENV 24 | VERSION=$(echo ${{ github.event.milestone.title }} | cut -d' ' -f2) 25 | echo "VERSION=$VERSION" >> $GITHUB_ENV 26 | 27 | - name: Create a Draft Release Notes on GitHub 28 | id: create_release 29 | uses: actions/create-release@v1 30 | env: 31 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token 32 | with: 33 | tag_name: ${{ env.VERSION }} 34 | release_name: ${{ env.VERSION }} 35 | body_path: ${{ env.RELEASE_NOTES_FILE }} 36 | draft: true 37 | -------------------------------------------------------------------------------- /.github/workflows/toc.yml: -------------------------------------------------------------------------------- 1 | on: push 2 | name: TOC Generator 3 | jobs: 4 | generateTOC: 5 | name: TOC Generator 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: technote-space/toc-generator@v4 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .idea/ 3 | .classpath 4 | .project 5 | .settings/ 6 | .meta-data/ 7 | .java-version 8 | .DS_Store 9 | target/ 10 | pom.xml.versionsBackup 11 | 12 | .mvn/wrapper/maven-wrapper.jar 13 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip 18 | -------------------------------------------------------------------------------- /.tool-versions: -------------------------------------------------------------------------------- 1 | java adopt-openjdk-11.0.8+10_openj9-0.21.0_large-heap 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | dist: trusty 3 | language: java 4 | 5 | jdk: 6 | - openjdk11 7 | 8 | install: true 9 | before_install: 10 | - chmod +x mvnw 11 | cache: 12 | directories: 13 | - $HOME/.m2 14 | 15 | script: ./mvnw clean verify 16 | after_success: 17 | - bash <(curl -s https://codecov.io/bash) 18 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guide 2 | 3 | There are several ways in which you may contribute to this project. 4 | 5 | * [File issues](https://github.com/camunda/camunda-bpm-mockito/issues) 6 | * [Submit a pull requests](#submit-a-pull-request) 7 | 8 | Read more on [how to get the project up and running](#project-setup). 9 | 10 | 11 | ## Submit a Pull Request 12 | 13 | If you would like to submit a pull request make sure to 14 | 15 | - add test cases for the problem you are solving 16 | - stick to project coding conventions 17 | 18 | 19 | ## Project Setup 20 | 21 | _Perform the following steps to get a development setup up and running._ 22 | 23 | - `git clone https://github.com/camunda/camunda-platform-7-mockito.git` 24 | - `cd camunda-platform-7-mockito` 25 | - `mvn clean package` 26 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:recommended" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/ProcessExpressions.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito; 2 | 3 | import org.camunda.bpm.engine.RuntimeService; 4 | import org.camunda.bpm.engine.runtime.MessageCorrelationBuilder; 5 | import org.camunda.community.mockito.message.MessageCorrelationBuilderMock; 6 | import org.camunda.community.mockito.process.CallActivityMock; 7 | 8 | import static org.mockito.ArgumentMatchers.any; 9 | 10 | public enum ProcessExpressions { 11 | ; 12 | 13 | /** 14 | * Registers a call activity mock for the given process definition key. 15 | * @param processDefinitionKey process definition key of the called process 16 | * @param mockedModelConfigurer configurer for adjusting the attributes of the mocked model 17 | * @return A mock for the called process (its behaviour should be configured via further calls) 18 | */ 19 | public static CallActivityMock registerCallActivityMock(final String processDefinitionKey, 20 | CallActivityMock.MockedModelConfigurer mockedModelConfigurer) { 21 | return new CallActivityMock(processDefinitionKey, mockedModelConfigurer); 22 | } 23 | 24 | /** 25 | * Registers a call activity mock for the given process definition key (without the possibility 26 | * to adjust the properties of the mocked model). 27 | * 28 | * @param processDefinitionKey process definition key of the called process 29 | * @return A mock for the called process (its behaviour should be configured via further calls) 30 | */ 31 | public static CallActivityMock registerCallActivityMock(final String processDefinitionKey) { 32 | return new CallActivityMock(processDefinitionKey); 33 | } 34 | 35 | /** 36 | * Registers the mock for message correlation. 37 | * 38 | * @param serviceMock runtime service mock. 39 | * @param messageName name of the message to mock message correlation for. 40 | * 41 | * @return mocked builder 42 | */ 43 | public static MessageCorrelationBuilder mockMessageCorrelation(final RuntimeService serviceMock, final String messageName) { 44 | return new MessageCorrelationBuilderMock().forServiceAndMessage(serviceMock, messageName).get(); 45 | } 46 | /** 47 | * Registers the mock for message correlation. 48 | * 49 | * @param serviceMock runtime service mock. 50 | * 51 | * @return mocked builder 52 | */ 53 | public static MessageCorrelationBuilder mockMessageCorrelation(final RuntimeService serviceMock) { 54 | return mockMessageCorrelation(serviceMock, any()); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/ServiceExpressions.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito; 2 | 3 | import org.camunda.bpm.engine.CaseService; 4 | import org.camunda.bpm.engine.RuntimeService; 5 | import org.camunda.bpm.engine.TaskService; 6 | import org.camunda.bpm.engine.variable.VariableMap; 7 | import org.camunda.community.mockito.service.CaseServiceStubBuilder; 8 | import org.camunda.community.mockito.service.RuntimeServiceStubBuilder; 9 | import org.camunda.community.mockito.service.TaskServiceStubBuilder; 10 | import org.camunda.community.mockito.verify.CaseServiceVerification; 11 | import org.camunda.community.mockito.verify.RuntimeServiceVerification; 12 | import org.camunda.community.mockito.verify.TaskServiceVerification; 13 | 14 | /** 15 | * Util class to access the helpers for mocking of Camunda Java Service API. 16 | */ 17 | public class ServiceExpressions { 18 | 19 | /** 20 | * Constructs a task service variable mock builder. 21 | * 22 | * @param taskService task service mock. 23 | * 24 | * @return fluent builder. 25 | */ 26 | public static TaskServiceStubBuilder taskServiceVariableStubBuilder(TaskService taskService) { 27 | return new TaskServiceStubBuilder(taskService); 28 | } 29 | 30 | /** 31 | * Constructs a task service variable mock builder. 32 | * 33 | * @param taskService task service mock. 34 | * @param variables variable map to reuse. 35 | * @param localVariables local variable map to reuse. 36 | * 37 | * @return fluent builder. 38 | */ 39 | public static TaskServiceStubBuilder taskServiceVariableStubBuilder(TaskService taskService, VariableMap variables, VariableMap localVariables) { 40 | return new TaskServiceStubBuilder(taskService, variables, localVariables); 41 | } 42 | 43 | /** 44 | * Creates verification for task service. 45 | * 46 | * @param taskService task service mock. 47 | * 48 | * @return verification. 49 | */ 50 | public static TaskServiceVerification taskServiceVerification(TaskService taskService) { 51 | return new TaskServiceVerification(taskService); 52 | } 53 | 54 | /** 55 | * Constructs a runtime service variable mock builder. 56 | * 57 | * @param runtimeService runtime service mock. 58 | * 59 | * @return fluent builder. 60 | */ 61 | public static RuntimeServiceStubBuilder runtimeServiceVariableStubBuilder(RuntimeService runtimeService) { 62 | return new RuntimeServiceStubBuilder(runtimeService); 63 | } 64 | 65 | /** 66 | * Constructs a runtime service variable mock builder. 67 | * 68 | * @param runtimeService runtime service mock. 69 | * @param variables variable map to reuse. 70 | * @param localVariables local variable map to reuse. 71 | * 72 | * @return fluent builder. 73 | */ 74 | public static RuntimeServiceStubBuilder runtimeServiceVariableStubBuilder(RuntimeService runtimeService, VariableMap variables, VariableMap localVariables) { 75 | return new RuntimeServiceStubBuilder(runtimeService, variables, localVariables); 76 | } 77 | 78 | /** 79 | * Creates verification for runtime service. 80 | * 81 | * @param runtimeService runtime service mock. 82 | * 83 | * @return verification. 84 | */ 85 | public static RuntimeServiceVerification runtimeServiceVerification(RuntimeService runtimeService) { 86 | return new RuntimeServiceVerification(runtimeService); 87 | } 88 | 89 | /** 90 | * Constructs a case service variable mock builder. 91 | * 92 | * @param caseService case service mock. 93 | * 94 | * @return fluent builder. 95 | */ 96 | public static CaseServiceStubBuilder caseServiceVariableStubBuilder(CaseService caseService) { 97 | return new CaseServiceStubBuilder(caseService); 98 | } 99 | 100 | /** 101 | * Constructs a case service variable mock builder. 102 | * 103 | * @param caseService case service mock. 104 | * @param variables variable map to reuse. 105 | * @param localVariables local variable map to reuse. 106 | * 107 | * @return fluent builder. 108 | */ 109 | public static CaseServiceStubBuilder caseServiceVariableStubBuilder(CaseService caseService, VariableMap variables, VariableMap localVariables) { 110 | return new CaseServiceStubBuilder(caseService, variables, localVariables); 111 | } 112 | 113 | /** 114 | * Creates verification for case service. 115 | * 116 | * @param caseService case service mock. 117 | * 118 | * @return verification. 119 | */ 120 | public static CaseServiceVerification caseServiceVerification(CaseService caseService) { 121 | return new CaseServiceVerification(caseService); 122 | } 123 | 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/answer/AbstractAnswer.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.answer; 2 | 3 | import org.camunda.bpm.engine.delegate.VariableScope; 4 | import org.mockito.invocation.InvocationOnMock; 5 | import org.mockito.stubbing.Answer; 6 | 7 | /** 8 | * Specialized {@link org.mockito.stubbing.Answer} that takes the single 9 | * argument of an execute() or notify() method and delegates to type safe call. 10 | * 11 | * @param 12 | * can be {@link org.camunda.bpm.engine.delegate.DelegateExecution} or 13 | * {@link org.camunda.bpm.engine.delegate.DelegateTask} 14 | */ 15 | abstract class AbstractAnswer implements Answer { 16 | 17 | @Override 18 | @SuppressWarnings("unchecked") 19 | public final Void answer(final InvocationOnMock invocation) throws Throwable { 20 | answer((T) invocation.getArguments()[0]); 21 | return null; 22 | } 23 | 24 | /** 25 | * Every implementing class must define what "answer" should actually do. 26 | * 27 | * @param parameter 28 | * either DelegateTask or DelegateExecution. 29 | * @throws Exception 30 | * when anything fails 31 | */ 32 | protected abstract void answer(T parameter) throws Exception; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/answer/ExecutionListenerAnswer.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.answer; 2 | 3 | import org.camunda.bpm.engine.delegate.DelegateExecution; 4 | import org.camunda.bpm.engine.delegate.ExecutionListener; 5 | 6 | /** 7 | * This is a specialized {@link org.mockito.stubbing.Answer} that delegates to 8 | * the given {@link org.camunda.bpm.engine.delegate.ExecutionListener}. When 9 | * using an ExecutionListener-Mock, this Answer can be used to implement 10 | * internal behavior of the mock by delegating the method call to the given 11 | * delegate instance. 12 | * 13 | * @author Jan Galinski, Holisticon AG 14 | */ 15 | public class ExecutionListenerAnswer extends AbstractAnswer implements ExecutionListener { 16 | 17 | private final ExecutionListener executionListener; 18 | 19 | public ExecutionListenerAnswer(final ExecutionListener executionListener) { 20 | this.executionListener = executionListener; 21 | } 22 | 23 | @Override 24 | public void notify(final DelegateExecution execution) throws Exception { 25 | executionListener.notify(execution); 26 | } 27 | 28 | @Override 29 | protected void answer(final DelegateExecution parameter) throws Exception { 30 | notify(parameter); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/answer/FluentAnswer.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.answer; 2 | 3 | import javax.annotation.Nonnull; 4 | 5 | import org.camunda.bpm.engine.query.Query; 6 | import org.mockito.Mockito; 7 | import org.mockito.invocation.InvocationOnMock; 8 | import org.mockito.stubbing.Answer; 9 | 10 | /** 11 | * A fluent answer always returns the mock instance itself for all methods that 12 | * have the same return type as the mock instance. This makes it possible to 13 | * easily mock fluent-api behaviour without chaining the when/then stubbings or 14 | * relying on deep stubs. 15 | * 16 | * @param 17 | * the return type of the answer 18 | */ 19 | public final class FluentAnswer, R extends Object> implements Answer { 20 | 21 | /** 22 | * Creates a new mock of given type with a fluent default answer already set 23 | * up. 24 | * 25 | * @param type 26 | * type of mock 27 | * @param 28 | * generic parameter for type of mock 29 | * @return new mock instance of type T with default fluent answer. 30 | */ 31 | public static , R extends Object> T createMock(Class type) { 32 | return Mockito.mock(type, createAnswer(type)); 33 | } 34 | 35 | /** 36 | * Creates a new instance for the given type. 37 | * 38 | * @param type 39 | * the return type of the answer 40 | * @param 41 | * generic parameter of the return type 42 | * @return new Answer that returns the mock itself 43 | */ 44 | public static , R extends Object> FluentAnswer createAnswer(Class type) { 45 | return new FluentAnswer(type); 46 | } 47 | 48 | /** 49 | * Holds the internal type. 50 | */ 51 | private final Class type; 52 | 53 | /** 54 | * Private constructor, use static factory methods to create. 55 | * 56 | * @param type 57 | * the type of the return value for the answer 58 | */ 59 | private FluentAnswer(Class type) { 60 | this.type = type; 61 | } 62 | 63 | /** 64 | * Returns the mock itself if return type and mock type match (assume fluent 65 | * api). 66 | * 67 | * @param invocation 68 | * the method invocation. If its return type equals the mock type, 69 | * just return the mock. 70 | * @return the mock itself or null (meaning further stubbing is required). 71 | * @throws Throwable 72 | * when anything fails 73 | */ 74 | @Override 75 | @SuppressWarnings("unchecked") 76 | public T answer(@Nonnull final InvocationOnMock invocation) throws Throwable { 77 | final Class methodReturnType = invocation.getMethod().getReturnType(); 78 | if (type.isAssignableFrom(methodReturnType) // fluent api methods 79 | || Query.class.isAssignableFrom(methodReturnType) // asc/desc 80 | ) { 81 | Object mock = invocation.getMock(); 82 | return (T)mock ; 83 | } 84 | return null; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/answer/FluentMessageCorrelationBuilderAnswer.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.answer; 2 | 3 | import org.camunda.bpm.engine.runtime.MessageCorrelationBuilder; 4 | import org.mockito.Mockito; 5 | import org.mockito.invocation.InvocationOnMock; 6 | import org.mockito.stubbing.Answer; 7 | 8 | import javax.annotation.Nonnull; 9 | 10 | /** 11 | * A fluent answer always returns the mock instance itself for all methods that 12 | * have the same return type as the mock instance. This makes it possible to 13 | * easily mock fluent-api behaviour without chaining the when/then stubbings or 14 | * relying on deep stubs. 15 | */ 16 | public final class FluentMessageCorrelationBuilderAnswer implements Answer { 17 | 18 | /** 19 | * Create builder mock with fluent answer. 20 | * 21 | * @return fluent mock. 22 | */ 23 | public static MessageCorrelationBuilder createMock() { 24 | return Mockito.mock(MessageCorrelationBuilder.class, new FluentMessageCorrelationBuilderAnswer()); 25 | } 26 | 27 | /** 28 | * Returns the mock itself if return type and mock type match (assume fluent 29 | * api). 30 | * 31 | * @param invocation the method invocation. If its return type equals the mock type, 32 | * just return the mock. 33 | * 34 | * @return the mock itself or null (meaning further stubbing is required). 35 | * 36 | * @throws Throwable when anything fails 37 | */ 38 | @Override 39 | @SuppressWarnings("unchecked") 40 | public MessageCorrelationBuilder answer(@Nonnull final InvocationOnMock invocation) throws Throwable { 41 | final Class methodReturnType = invocation.getMethod().getReturnType(); 42 | if (MessageCorrelationBuilder.class.isAssignableFrom(methodReturnType)) { 43 | // fluent api methods 44 | Object mock = invocation.getMock(); 45 | return (MessageCorrelationBuilder) mock; 46 | } 47 | return null; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/answer/JavaDelegateAnswer.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.answer; 2 | 3 | import org.camunda.bpm.engine.delegate.DelegateExecution; 4 | import org.camunda.bpm.engine.delegate.JavaDelegate; 5 | 6 | /** 7 | * This is a specialized {@link org.mockito.stubbing.Answer} that delegates to 8 | * the given {@link org.camunda.bpm.engine.delegate.JavaDelegate}. When using an 9 | * JavaDelegate-Mock, this Answer can be used to implement internal behavior of 10 | * the mock by delegating the method call to the given delegate instance. 11 | * 12 | * @author Jan Galinski, Holisticon AG 13 | */ 14 | public class JavaDelegateAnswer extends AbstractAnswer implements JavaDelegate { 15 | 16 | private final JavaDelegate javaDelegate; 17 | 18 | public JavaDelegateAnswer(final JavaDelegate javaDelegate) { 19 | this.javaDelegate = javaDelegate; 20 | } 21 | 22 | @Override 23 | public void execute(final DelegateExecution execution) throws Exception { 24 | javaDelegate.execute(execution); 25 | } 26 | 27 | @Override 28 | protected void answer(final DelegateExecution delegateExecution) throws Exception { 29 | execute(delegateExecution); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/answer/TaskListenerAnswer.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.answer; 2 | 3 | import org.camunda.bpm.engine.delegate.DelegateTask; 4 | import org.camunda.bpm.engine.delegate.TaskListener; 5 | 6 | /** 7 | * This is a specialized {@link org.mockito.stubbing.Answer} that delegates to 8 | * the given {@link org.camunda.bpm.engine.delegate.TaskListener}. When using an 9 | * TaskListener-Mock, this Answer can be used to implement internal behavior of 10 | * the mock by delegating the method call to the given delegate instance. 11 | * 12 | * @author Jan Galinski, Holisticon AG 13 | */ 14 | public class TaskListenerAnswer extends AbstractAnswer implements TaskListener { 15 | 16 | private final TaskListener taskListener; 17 | 18 | public TaskListenerAnswer(final TaskListener taskListener) { 19 | this.taskListener = taskListener; 20 | } 21 | 22 | @Override 23 | public void notify(final DelegateTask delegateTask) { 24 | taskListener.notify(delegateTask); 25 | } 26 | 27 | @Override 28 | protected void answer(final DelegateTask delegateTask) throws Exception { 29 | notify(delegateTask); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/cases/CaseExecutionEntityFake.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.cases; 2 | 3 | 4 | import org.camunda.bpm.engine.impl.cmmn.entity.runtime.CaseExecutionEntity; 5 | import org.camunda.bpm.engine.impl.cmmn.execution.CaseExecutionState; 6 | 7 | import java.util.concurrent.atomic.AtomicInteger; 8 | 9 | import static org.camunda.bpm.engine.impl.cmmn.execution.CaseExecutionState.DISABLED; 10 | import static org.camunda.bpm.engine.impl.cmmn.execution.CaseExecutionState.ENABLED; 11 | 12 | public class CaseExecutionEntityFake extends CaseExecutionEntity { 13 | 14 | private static final AtomicInteger count = new AtomicInteger(); 15 | 16 | public CaseExecutionEntityFake(String activityId) { 17 | id = String.valueOf(count.getAndIncrement()); 18 | this.activityId = activityId; 19 | } 20 | 21 | public CaseExecutionEntityFake setState(CaseExecutionState state) { 22 | currentState = state.getStateCode(); 23 | return this; 24 | } 25 | 26 | @Override 27 | public void enable() { 28 | setState(ENABLED); 29 | } 30 | 31 | @Override 32 | public void disable() { 33 | setState(DISABLED); 34 | } 35 | 36 | @Override 37 | public void reenable() { 38 | setState(ENABLED); 39 | } 40 | 41 | @Override 42 | public String toString() { 43 | return "CaseExecutionEntityFake{" + 44 | "id='" + id + '\'' + 45 | ", state='" + getCurrentState() + '\'' + 46 | '}'; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/cases/CaseInstanceFakeBuilder.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.cases; 2 | 3 | import org.camunda.bpm.engine.variable.VariableMap; 4 | import org.camunda.bpm.engine.variable.Variables; 5 | 6 | public class CaseInstanceFakeBuilder { 7 | private boolean disabled = false; 8 | private boolean terminated = false; 9 | private boolean completed = false; 10 | private boolean required = false; 11 | private boolean enabled = false; 12 | private boolean active = false; 13 | private boolean available = false; 14 | private String businessKey; 15 | private String id; 16 | private String caseInstanceId; 17 | private String caseDefinitionId; 18 | private String activityId; 19 | private String activityName; 20 | private String activityType; 21 | private String parentId; 22 | private String activityDescription; 23 | private String tenantId; 24 | private final VariableMap variables = Variables.createVariables(); 25 | 26 | public CaseInstanceFakeBuilder disabled(boolean disabled) { 27 | this.disabled = disabled; 28 | return this; 29 | } 30 | 31 | public CaseInstanceFakeBuilder terminated(boolean terminated) { 32 | this.terminated = terminated; 33 | return this; 34 | } 35 | 36 | public CaseInstanceFakeBuilder completed(boolean completed) { 37 | this.completed = completed; 38 | return this; 39 | } 40 | 41 | public CaseInstanceFakeBuilder required(boolean required) { 42 | this.required = required; 43 | return this; 44 | } 45 | 46 | public CaseInstanceFakeBuilder enabled(boolean enabled) { 47 | this.enabled = enabled; 48 | return this; 49 | } 50 | 51 | public CaseInstanceFakeBuilder active(boolean active) { 52 | this.active = active; 53 | return this; 54 | } 55 | 56 | public CaseInstanceFakeBuilder available(boolean available) { 57 | this.available = available; 58 | return this; 59 | } 60 | 61 | public CaseInstanceFakeBuilder businessKey(String businessKey) { 62 | this.businessKey = businessKey; 63 | return this; 64 | } 65 | 66 | public CaseInstanceFakeBuilder id(String id) { 67 | this.id = id; 68 | return this; 69 | } 70 | 71 | public CaseInstanceFakeBuilder caseInstanceId(String caseInstanceId) { 72 | this.caseInstanceId = caseInstanceId; 73 | return this; 74 | } 75 | 76 | public CaseInstanceFakeBuilder caseDefinitionId(String caseDefinitionId) { 77 | this.caseDefinitionId = caseDefinitionId; 78 | return this; 79 | } 80 | 81 | public CaseInstanceFakeBuilder activityId(String activityId) { 82 | this.activityId = activityId; 83 | return this; 84 | } 85 | 86 | public CaseInstanceFakeBuilder activityName(String activityName) { 87 | this.activityName = activityName; 88 | return this; 89 | } 90 | 91 | public CaseInstanceFakeBuilder activityType(String activityType) { 92 | this.activityType = activityType; 93 | return this; 94 | } 95 | 96 | public CaseInstanceFakeBuilder parentId(String parentId) { 97 | this.parentId = parentId; 98 | return this; 99 | } 100 | 101 | public CaseInstanceFakeBuilder activityDescription(String activityDescription) { 102 | this.activityDescription = activityDescription; 103 | return this; 104 | } 105 | 106 | public CaseInstanceFakeBuilder tenantId(String tenantId) { 107 | this.tenantId = tenantId; 108 | return this; 109 | } 110 | 111 | public CaseInstanceFakeBuilder variable(String key, Object value) { 112 | variables.putValue(key, value); 113 | return this; 114 | } 115 | 116 | @Override 117 | public String toString() { 118 | return "CaseInstanceFakeBuilder{" + 119 | "disabled=" + disabled + 120 | ", terminated=" + terminated + 121 | ", completed=" + completed + 122 | ", required=" + required + 123 | ", enabled=" + enabled + 124 | ", active=" + active + 125 | ", available=" + available + 126 | ", businessKey='" + businessKey + '\'' + 127 | ", id='" + id + '\'' + 128 | ", caseInstanceId='" + caseInstanceId + '\'' + 129 | ", caseDefinitionId='" + caseDefinitionId + '\'' + 130 | ", activityId='" + activityId + '\'' + 131 | ", activityName='" + activityName + '\'' + 132 | ", activityType='" + activityType + '\'' + 133 | ", parentId='" + parentId + '\'' + 134 | ", activityDescription='" + activityDescription + '\'' + 135 | ", tenantId='" + tenantId + '\'' + 136 | '}'; 137 | } 138 | 139 | public CaseInstanceFake build() { 140 | return new CaseInstanceFake( 141 | disabled, terminated, completed, required, enabled, 142 | active, available, businessKey, id, caseInstanceId, 143 | caseDefinitionId, activityId, activityName, activityType, 144 | parentId, activityDescription, tenantId, variables 145 | ); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/delegate/DelegateFake.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.delegate; 2 | 3 | import org.camunda.bpm.engine.ProcessEngine; 4 | import org.camunda.bpm.engine.ProcessEngineServices; 5 | import org.camunda.bpm.engine.delegate.ProcessEngineServicesAware; 6 | 7 | abstract class DelegateFake extends VariableScopeFake implements ProcessEngineServicesAware { 8 | 9 | protected final ProcessEngineServicesAwareFake processEngineServicesAwareFake = new ProcessEngineServicesAwareFake(); 10 | 11 | @Override 12 | public ProcessEngineServices getProcessEngineServices() { 13 | return processEngineServicesAwareFake.getProcessEngineServices(); 14 | } 15 | 16 | public T withProcessEngineServices(ProcessEngineServices processEngineServices) { 17 | processEngineServicesAwareFake.withProcessEngineServices(processEngineServices); 18 | return (T) this; 19 | } 20 | 21 | 22 | @Override 23 | public ProcessEngine getProcessEngine() { 24 | return processEngineServicesAwareFake.getProcessEngine(); 25 | } 26 | 27 | public T withProcessEngine(ProcessEngine processEngine) { 28 | processEngineServicesAwareFake.withProcessEngine(processEngine); 29 | return (T) this; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/delegate/IncidentFake.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.delegate; 2 | 3 | import org.camunda.bpm.engine.runtime.Incident; 4 | 5 | import java.util.Date; 6 | import java.util.UUID; 7 | 8 | public class IncidentFake implements Incident { 9 | 10 | private final String id = UUID.randomUUID().toString(); 11 | private final Date timestamp = new Date(); 12 | 13 | private final DelegateExecutionFake execution; 14 | private final String type; 15 | private final String message; 16 | private final String configuration; 17 | private final String jobDefinitionId; 18 | private final String historyConfiguration; 19 | private final String failedActivityId; 20 | private final String annotation; 21 | 22 | public IncidentFake(DelegateExecutionFake execution, String type, String configuration, String message, String jobDefinitionId, String historyConfiguration, String failedActivityId, String annotation) { 23 | this.execution = execution; 24 | this.type = type; 25 | this.configuration = configuration; 26 | this.message = message; 27 | this.jobDefinitionId = jobDefinitionId; 28 | this.historyConfiguration = historyConfiguration; 29 | this.failedActivityId = failedActivityId; 30 | this.annotation = annotation; 31 | } 32 | 33 | 34 | @Override 35 | public String getId() { 36 | return id; 37 | } 38 | 39 | @Override 40 | public Date getIncidentTimestamp() { 41 | return timestamp; 42 | } 43 | 44 | @Override 45 | public String getIncidentType() { 46 | return type; 47 | } 48 | 49 | @Override 50 | public String getIncidentMessage() { 51 | return message; 52 | } 53 | 54 | @Override 55 | public String getExecutionId() { 56 | return execution.getId(); 57 | } 58 | 59 | @Override 60 | public String getActivityId() { 61 | return execution.getCurrentActivityId(); 62 | } 63 | 64 | @Override 65 | public String getFailedActivityId() { 66 | return failedActivityId; 67 | } 68 | 69 | @Override 70 | public String getProcessInstanceId() { 71 | return execution.getProcessInstanceId(); 72 | } 73 | 74 | @Override 75 | public String getProcessDefinitionId() { 76 | return execution.getProcessDefinitionId(); 77 | } 78 | 79 | @Override 80 | public String getCauseIncidentId() { 81 | return id; 82 | } 83 | 84 | @Override 85 | public String getRootCauseIncidentId() { 86 | return id; 87 | } 88 | 89 | @Override 90 | public String getConfiguration() { 91 | return configuration; 92 | } 93 | 94 | @Override 95 | public String getTenantId() { 96 | return execution.getTenantId(); 97 | } 98 | 99 | @Override 100 | public String getJobDefinitionId() { 101 | return jobDefinitionId; 102 | } 103 | 104 | @Override 105 | public String getHistoryConfiguration() { 106 | return historyConfiguration; 107 | } 108 | 109 | @Override 110 | public String getAnnotation() { 111 | return annotation; 112 | } 113 | 114 | 115 | @Override public String toString() { 116 | return "IncidentFake{" + 117 | "id='" + id + '\'' + 118 | ", timestamp=" + timestamp + 119 | ", execution=" + execution + 120 | ", type='" + type + '\'' + 121 | ", message='" + message + '\'' + 122 | ", configuration='" + configuration + '\'' + 123 | ", jobDefinitionId='" + jobDefinitionId + '\'' + 124 | ", historyConfiguration='" + historyConfiguration + '\'' + 125 | ", failedActivityId='" + failedActivityId + '\'' + 126 | ", annotation='" + annotation + '\'' + 127 | '}'; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/delegate/ProcessEngineServicesAwareFake.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.delegate; 2 | 3 | import org.camunda.bpm.engine.ProcessEngine; 4 | import org.camunda.bpm.engine.ProcessEngineServices; 5 | import org.camunda.bpm.engine.delegate.ProcessEngineServicesAware; 6 | 7 | public class ProcessEngineServicesAwareFake implements ProcessEngineServicesAware { 8 | 9 | private ProcessEngine processEngine; 10 | private ProcessEngineServices processEngineServices; 11 | 12 | @Override 13 | public ProcessEngineServices getProcessEngineServices() { 14 | return processEngineServices; 15 | } 16 | 17 | public ProcessEngineServicesAwareFake withProcessEngineServices(ProcessEngineServices processEngineServices) { 18 | this.processEngineServices = processEngineServices; 19 | return this; 20 | } 21 | 22 | @Override 23 | public ProcessEngine getProcessEngine() { 24 | return processEngine; 25 | } 26 | 27 | public ProcessEngineServicesAwareFake withProcessEngine(ProcessEngine processEngine) { 28 | this.processEngine = processEngine; 29 | return withProcessEngineServices(processEngine); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/delegate/VariableScopeFake.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.delegate; 2 | 3 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 4 | import org.camunda.bpm.engine.delegate.VariableScope; 5 | import org.camunda.bpm.engine.impl.core.variable.CoreVariableInstance; 6 | import org.camunda.bpm.engine.impl.core.variable.scope.*; 7 | 8 | import java.util.Collections; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | @SuppressWarnings("unchecked") 13 | public abstract class VariableScopeFake extends AbstractVariableScope implements VariableScope { 14 | 15 | protected VariableStore variableStore = new VariableStore<>(); 16 | protected VariableInstanceFactory variableInstanceFactory = (name, value, isTransient) -> new SimpleVariableInstance(name, value); 17 | 18 | @Override 19 | protected VariableStore getVariableStore() { 20 | return variableStore; 21 | } 22 | 23 | @Override 24 | protected VariableInstanceFactory getVariableInstanceFactory() { 25 | return variableInstanceFactory; 26 | } 27 | 28 | @Override 29 | public String getVariableScopeKey() { 30 | return "fake"; 31 | } 32 | 33 | @Override 34 | protected List> getVariableInstanceLifecycleListeners() { 35 | return Collections.EMPTY_LIST; 36 | } 37 | 38 | @Override 39 | public AbstractVariableScope getParentVariableScope() { 40 | return null; 41 | } 42 | 43 | public T withVariable(String variableName, Object value) { 44 | setVariable(variableName, value); 45 | return (T) this; 46 | } 47 | 48 | public T withVariableLocal(String variableName, Object value) { 49 | setVariableLocal(variableName, value); 50 | return (T) this; 51 | } 52 | 53 | public T withVariable(VariableFactory variable, V value) { 54 | variable.on(this).set(value); 55 | return (T) this; 56 | } 57 | 58 | public T withVariableLocal(VariableFactory variable, V value) { 59 | variable.on(this).setLocal(value); 60 | return (T) this; 61 | } 62 | 63 | public T withVariables(Map variables) { 64 | setVariables(variables); 65 | return (T) this; 66 | } 67 | 68 | public T withVariablesLocal(Map variables) { 69 | setVariablesLocal(variables); 70 | return (T) this; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/function/CreateInstance.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.function; 2 | 3 | import org.mockito.Mockito; 4 | 5 | /** 6 | * Helper to create either mock() or new() instances for given type. 7 | */ 8 | public final class CreateInstance { 9 | 10 | public static T mockInstance(final Class type) { 11 | return Mockito.mock(type); 12 | } 13 | 14 | @SuppressWarnings("unchecked") 15 | public static T newInstanceByDefaultConstructor(final Class type) { 16 | try { 17 | return (T) type.getConstructors()[0].newInstance(); 18 | } catch (final Exception e) { 19 | throw new RuntimeException(e); 20 | } 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/function/DeployProcess.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.function; 2 | 3 | import org.camunda.bpm.engine.ProcessEngineServices; 4 | import org.camunda.bpm.engine.RepositoryService; 5 | import org.camunda.bpm.engine.repository.Deployment; 6 | import org.camunda.bpm.engine.repository.DeploymentBuilder; 7 | import org.camunda.bpm.model.bpmn.BpmnModelInstance; 8 | 9 | import java.util.Arrays; 10 | import java.util.function.BiFunction; 11 | 12 | public class DeployProcess implements BiFunction { 13 | 14 | public interface BpmnModelInstanceResource { 15 | String getResourceName(); 16 | BpmnModelInstance getModelInstance(); 17 | 18 | default DeploymentBuilder addToDeployment(DeploymentBuilder builder) { 19 | builder.addModelInstance(getResourceName(), getModelInstance()); 20 | return builder; 21 | } 22 | } 23 | 24 | private final RepositoryService repositoryService; 25 | 26 | public DeployProcess(RepositoryService repositoryService) { 27 | this.repositoryService = repositoryService; 28 | } 29 | 30 | public DeployProcess(ProcessEngineServices processEngineServices) { 31 | this(processEngineServices.getRepositoryService()); 32 | } 33 | 34 | public Deployment apply(BpmnModelInstanceResource... modelInstanceResources) { 35 | final DeploymentBuilder builder = repositoryService.createDeployment(); 36 | Arrays.stream(modelInstanceResources).forEach(r -> r.addToDeployment(builder)); 37 | return builder.deploy(); 38 | } 39 | 40 | 41 | public Deployment apply(String processId, BpmnModelInstance instance) { 42 | return apply(new BpmnModelInstanceResource() { 43 | @Override 44 | public String getResourceName() { 45 | return processId + ".bpmn"; 46 | } 47 | 48 | @Override 49 | public BpmnModelInstance getModelInstance() { 50 | return instance; 51 | } 52 | }); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/function/GetProcessEngineConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.function; 2 | 3 | 4 | import java.util.function.Function; 5 | 6 | import org.camunda.bpm.engine.ProcessEngine; 7 | import org.camunda.bpm.engine.ProcessEngineConfiguration; 8 | import org.camunda.bpm.engine.impl.ProcessEngineImpl; 9 | 10 | /** 11 | * Hides the nasty "getConfiguration from given Engine Hack" in an easy to use 12 | * function. 13 | */ 14 | public enum GetProcessEngineConfiguration implements Function { 15 | INSTANCE; 16 | 17 | @Override 18 | public ProcessEngineConfiguration apply(final ProcessEngine processEngine) { 19 | if (!(processEngine instanceof ProcessEngineImpl)) { 20 | throw new IllegalArgumentException("processEngine must not be null and of type ProcessEngineImpl!"); 21 | } 22 | 23 | return ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/function/NameForType.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.function; 2 | 3 | import static org.apache.commons.lang3.StringUtils.isNotBlank; 4 | import static org.apache.commons.lang3.StringUtils.uncapitalize; 5 | 6 | import javax.annotation.Nullable; 7 | 8 | import java.lang.annotation.Annotation; 9 | import java.util.Arrays; 10 | import java.util.HashSet; 11 | import java.util.Optional; 12 | import java.util.Set; 13 | import java.util.function.Function; 14 | import java.util.function.Predicate; 15 | import java.util.stream.Stream; 16 | 17 | 18 | /** 19 | * Retrieves the juel expression for given type. First guess is the value of a @Named 20 | * annotation if present, otherwise, the uncapitalized SimpleName of the type is 21 | * returned. 22 | */ 23 | public enum NameForType implements Function, String> { 24 | INSTANCE; 25 | 26 | static final String ENHANCER = "$MockitoMock$"; 27 | 28 | /** 29 | * Does instance.getClass() but is mock-aware. 30 | * 31 | * @param instance the instance to get the class of 32 | * @return class name 33 | */ 34 | static Class typeOf(Object instance) { 35 | Class type = instance.getClass(); 36 | while (type.getSimpleName().contains(ENHANCER)) { 37 | type = type.getSuperclass(); 38 | } 39 | 40 | return type; 41 | } 42 | 43 | public static String juelNameFor(final Object instance) { 44 | if (instance == null) { 45 | throw new IllegalArgumentException("instance must not be null"); 46 | } 47 | return juelNameFor(typeOf(instance)); 48 | } 49 | 50 | public static String juelNameFor(final Class type) { 51 | return INSTANCE.apply(type); 52 | } 53 | 54 | static Function GET_VALUE = new Function() { 55 | @Nullable 56 | @Override 57 | public String apply(final Annotation annotation) { 58 | try { 59 | return (String) annotation.annotationType().getMethod("value").invoke(annotation); 60 | } catch (Exception e) { 61 | return ""; 62 | } 63 | } 64 | }; 65 | 66 | static Predicate IS_SUPPORTED = new Predicate() { 67 | private final Set NAME_ANNOTATIONS = new HashSet<>( 68 | Arrays.asList( 69 | "javax.inject.Named", 70 | "org.springframework.stereotype.Component", 71 | "org.springframework.stereotype.Service") 72 | ); 73 | 74 | @Override 75 | public boolean test(@Nullable Annotation a) { 76 | return NAME_ANNOTATIONS.contains(a.annotationType().getName()); 77 | } 78 | }; 79 | 80 | @Override 81 | public String apply(final Class type) { 82 | if (type == null) { 83 | throw new IllegalArgumentException("type must not be null!"); 84 | } 85 | final Optional value = Stream.of(type.getAnnotations()).filter(IS_SUPPORTED).findFirst().map(GET_VALUE); 86 | 87 | return value.isPresent() && isNotBlank(value.get()) ? value.get() : uncapitalize(type.getSimpleName()); 88 | } 89 | 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/function/NodeToString.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.function; 2 | 3 | 4 | import java.io.StringWriter; 5 | import java.util.function.Function; 6 | 7 | import javax.xml.transform.OutputKeys; 8 | import javax.xml.transform.Transformer; 9 | import javax.xml.transform.TransformerConfigurationException; 10 | import javax.xml.transform.TransformerException; 11 | import javax.xml.transform.TransformerFactory; 12 | import javax.xml.transform.dom.DOMSource; 13 | import javax.xml.transform.stream.StreamResult; 14 | 15 | import org.w3c.dom.Node; 16 | 17 | /** 18 | * Returns String representation of given DOM node. 19 | * 20 | * @author Jan Galinski, Holisticon AG 21 | */ 22 | class NodeToString implements Function { 23 | public static final NodeToString INSTANCE = new NodeToString(); 24 | 25 | private final Transformer transformer; 26 | 27 | private NodeToString() { 28 | try { 29 | transformer = TransformerFactory.newInstance().newTransformer(); 30 | transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 31 | } catch (TransformerConfigurationException e) { 32 | throw new RuntimeException(e); 33 | } 34 | } 35 | 36 | @Override 37 | public String apply(final Node document) { 38 | final StringWriter writer = new StringWriter(); 39 | try { 40 | transformer.transform(new DOMSource(document), new StreamResult(writer)); 41 | 42 | return writer.toString(); 43 | } catch (TransformerException e) { 44 | throw new RuntimeException(e); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/function/ParseDelegateExpressions.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.function; 2 | 3 | import static org.apache.commons.lang3.StringUtils.isNotBlank; 4 | import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.CAMUNDA_ATTRIBUTE_DELEGATE_EXPRESSION; 5 | import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.CAMUNDA_ELEMENT_EXECUTION_LISTENER; 6 | import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.CAMUNDA_ELEMENT_TASK_LISTENER; 7 | 8 | import java.net.URL; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.Optional; 12 | import java.util.function.Function; 13 | 14 | import org.apache.commons.lang3.tuple.Pair; 15 | import org.camunda.community.mockito.DelegateExpressions; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | import org.w3c.dom.Element; 19 | import org.w3c.dom.NamedNodeMap; 20 | import org.w3c.dom.Node; 21 | import org.w3c.dom.NodeList; 22 | 23 | /** 24 | * Parses a given BPMN File and returns a Set of all delegateExpression names. 25 | * 26 | * @author Jan Galinski, Holisticon AG 27 | */ 28 | public class ParseDelegateExpressions implements Function>> { 29 | 30 | public static enum ExpressionType { 31 | EXECUTION_LISTENER(CAMUNDA_ELEMENT_EXECUTION_LISTENER) { 32 | @Override 33 | public void registerMock(final String name) { 34 | DelegateExpressions.registerExecutionListenerMock(name); 35 | } 36 | }, TASK_LISTENER(CAMUNDA_ELEMENT_TASK_LISTENER) { 37 | @Override 38 | public void registerMock(final String name) { 39 | DelegateExpressions.registerTaskListenerMock(name); 40 | } 41 | }, JAVA_DELEGATE("serviceTask") { 42 | @Override 43 | public void registerMock(final String name) { 44 | DelegateExpressions.registerJavaDelegateMock(name); 45 | } 46 | }; 47 | 48 | private final String element; 49 | 50 | ExpressionType(final String element) { 51 | this.element = element; 52 | } 53 | 54 | public abstract void registerMock(final String name); 55 | } 56 | 57 | /** 58 | * Regex to extract the delegateExpression name (#{hello} -> hello). 59 | */ 60 | static final String PATTERN_DELEGATE_EXPRESSION = "[#$]\\{([^}]+)}"; 61 | 62 | public static String extractDelegateExpressionName(final String delegateExpression) { 63 | return isNotBlank(delegateExpression) ? delegateExpression.replaceAll(PATTERN_DELEGATE_EXPRESSION, "$1") : null; 64 | } 65 | 66 | private final Logger logger = LoggerFactory.getLogger(getClass()); 67 | private final ReadXmlDocumentFromResource readXmlDocumentFromResource = new ReadXmlDocumentFromResource(); 68 | 69 | @Override 70 | public List> apply(final URL bpmnResource) { 71 | final Element root = new ReadXmlDocumentFromResource().apply(bpmnResource).getDocumentElement(); 72 | 73 | return new ArrayList>() { 74 | { 75 | for (ExpressionType type : ExpressionType.values()) { 76 | final NodeList nodes = root.getElementsByTagNameNS("*", type.element); 77 | 78 | for (int i = 0; i < nodes.getLength(); i++) { 79 | final NamedNodeMap attributes = nodes.item(i).getAttributes(); 80 | 81 | // TODO: this is not nice, but I cannot get getNamedItemNS("*", ...) to work properly 82 | Node delegateExpression = Optional 83 | .ofNullable(attributes.getNamedItem(CAMUNDA_ATTRIBUTE_DELEGATE_EXPRESSION)) 84 | .orElse(attributes.getNamedItem("camunda:"+CAMUNDA_ATTRIBUTE_DELEGATE_EXPRESSION)); 85 | 86 | if (delegateExpression != null) { 87 | add(Pair.of(type, extractDelegateExpressionName(delegateExpression.getTextContent()))); 88 | } 89 | } 90 | 91 | } 92 | } 93 | }; 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/function/ReadXmlDocumentFromResource.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.function; 2 | 3 | 4 | import java.io.IOException; 5 | import java.io.StringWriter; 6 | import java.net.URL; 7 | import java.util.function.Function; 8 | 9 | import javax.annotation.Nonnull; 10 | import javax.xml.parsers.DocumentBuilderFactory; 11 | import javax.xml.parsers.ParserConfigurationException; 12 | import javax.xml.transform.OutputKeys; 13 | import javax.xml.transform.Transformer; 14 | import javax.xml.transform.TransformerFactory; 15 | import javax.xml.transform.dom.DOMSource; 16 | import javax.xml.transform.stream.StreamResult; 17 | 18 | import org.w3c.dom.Document; 19 | import org.xml.sax.SAXException; 20 | 21 | 22 | /** 23 | * Return DOM document for given resource. 24 | * 25 | * @author Jan Galinski, Holisticon AG 26 | */ 27 | public class ReadXmlDocumentFromResource implements Function { 28 | 29 | public static Function TO_STRING = new Function() { 30 | @Nonnull 31 | @Override 32 | public String apply(final Document document) { 33 | try { 34 | Transformer transformer = TransformerFactory.newInstance().newTransformer(); 35 | transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 36 | final StringWriter writer = new StringWriter(); 37 | transformer.transform(new DOMSource(document), new StreamResult(writer)); 38 | return writer.getBuffer().toString(); 39 | } catch (javax.xml.transform.TransformerException e) { 40 | throw new RuntimeException(e); 41 | } 42 | 43 | } 44 | }; 45 | 46 | private final DocumentBuilderFactory factory; 47 | 48 | public ReadXmlDocumentFromResource() { 49 | this.factory = DocumentBuilderFactory.newInstance(); 50 | factory.setNamespaceAware(true); 51 | } 52 | 53 | @Override 54 | public Document apply(final URL xmlResource) { 55 | try { 56 | final Document document = factory.newDocumentBuilder().parse(xmlResource.openStream()); 57 | document.getDocumentElement().normalize(); 58 | 59 | return document; 60 | } catch (Exception e) { 61 | throw new RuntimeException(e); 62 | } 63 | 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/message/MessageCorrelationBuilderMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.message; 2 | 3 | import org.camunda.bpm.engine.RuntimeService; 4 | import org.camunda.bpm.engine.runtime.MessageCorrelationBuilder; 5 | import org.camunda.community.mockito.answer.FluentMessageCorrelationBuilderAnswer; 6 | 7 | import java.util.function.Supplier; 8 | 9 | import static org.mockito.Mockito.when; 10 | 11 | public class MessageCorrelationBuilderMock implements Supplier { 12 | 13 | private final MessageCorrelationBuilder builder; 14 | 15 | public MessageCorrelationBuilderMock() { 16 | builder = FluentMessageCorrelationBuilderAnswer.createMock(); 17 | } 18 | 19 | @Override 20 | public MessageCorrelationBuilder get() { 21 | return builder; 22 | } 23 | 24 | /** 25 | * Create and register a mock for mocked runtimeService and a message name. 26 | * 27 | * @param service mocked runtime service. 28 | * @param messageName message name to register the fluent builder for. 29 | * 30 | * @return mock 31 | */ 32 | public MessageCorrelationBuilderMock forServiceAndMessage(RuntimeService service, String messageName) { 33 | 34 | try { 35 | when(service.createMessageCorrelation(messageName)).thenReturn(get()); 36 | } catch (Exception e) { 37 | throw new RuntimeException(e); 38 | } 39 | 40 | return this; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/mock/FluentExecutionListenerMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.mock; 2 | 3 | import static org.mockito.Mockito.mock; 4 | 5 | import org.camunda.bpm.engine.delegate.BpmnError; 6 | import org.camunda.bpm.engine.delegate.DelegateExecution; 7 | import org.camunda.bpm.engine.delegate.ExecutionListener; 8 | import org.camunda.bpm.engine.variable.VariableMap; 9 | import org.camunda.community.mockito.answer.ExecutionListenerAnswer; 10 | import org.mockito.Mockito; 11 | 12 | import java.util.UUID; 13 | 14 | public class FluentExecutionListenerMock extends FluentMock implements ExecutionListener { 15 | 16 | public FluentExecutionListenerMock() { 17 | super(mock(ExecutionListener.class), DelegateExecution.class); 18 | } 19 | 20 | @Override 21 | public void onExecutionSetVariables(final VariableMap variables) { 22 | doAnswer(new ExecutionListener() { 23 | 24 | @Override 25 | public void notify(final DelegateExecution execution) throws Exception { 26 | setVariables(execution, variables); 27 | } 28 | }); 29 | } 30 | 31 | @Override 32 | public void onExecutionSetVariables(VariableMap variableMap, VariableMap... values) { 33 | try { 34 | final String countVariable = UUID.randomUUID().toString(); 35 | Mockito.doAnswer( 36 | new ExecutionListenerAnswer(execution -> setVariablesForMultipleInvocations(combineVariableMaps(variableMap, values), 37 | countVariable, 38 | execution)) 39 | ).when(mock).notify(any()); 40 | } catch (final Exception e) { 41 | throw new RuntimeException(e); 42 | } 43 | } 44 | 45 | @Override 46 | public void onExecutionThrowBpmnError(final BpmnError bpmnError) { 47 | doAnswer(new ExecutionListener() { 48 | 49 | @Override 50 | public void notify(final DelegateExecution execution) throws Exception { 51 | throw bpmnError; 52 | } 53 | }); 54 | } 55 | 56 | @Override 57 | public void onExecutionThrowException(final Exception exception) { 58 | doAnswer(new ExecutionListener() { 59 | @Override 60 | public void notify(DelegateExecution execution) throws Exception { 61 | throw exception; 62 | } 63 | }); 64 | } 65 | 66 | @Override 67 | public void notify(final DelegateExecution execution) throws Exception { 68 | mock.notify(execution); 69 | } 70 | 71 | private void doAnswer(final ExecutionListener executionListener) { 72 | try { 73 | Mockito.doAnswer(new ExecutionListenerAnswer(executionListener)).when(mock).notify(any()); 74 | } catch (final Exception e) { 75 | throw new RuntimeException(e); 76 | } 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/mock/FluentJavaDelegateMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.mock; 2 | 3 | import static org.mockito.Mockito.mock; 4 | 5 | import org.camunda.bpm.engine.delegate.BpmnError; 6 | import org.camunda.bpm.engine.delegate.DelegateExecution; 7 | import org.camunda.bpm.engine.delegate.JavaDelegate; 8 | import org.camunda.bpm.engine.variable.VariableMap; 9 | import org.camunda.community.mockito.answer.JavaDelegateAnswer; 10 | import org.mockito.Mockito; 11 | 12 | import java.util.UUID; 13 | 14 | public class FluentJavaDelegateMock extends FluentMock implements JavaDelegate { 15 | 16 | public FluentJavaDelegateMock() { 17 | super(mock(JavaDelegate.class), DelegateExecution.class); 18 | } 19 | 20 | @Override 21 | public void execute(final DelegateExecution execution) throws Exception { 22 | mock.execute(execution); 23 | } 24 | 25 | @Override 26 | public void onExecutionSetVariables(final VariableMap variables) { 27 | doAnswer(new JavaDelegate() { 28 | 29 | @Override 30 | public void execute(final DelegateExecution execution) throws Exception { 31 | setVariables(execution, variables); 32 | } 33 | }); 34 | } 35 | 36 | @Override 37 | public void onExecutionSetVariables(VariableMap variableMap, VariableMap... values) { 38 | try { 39 | final String countVariable = UUID.randomUUID().toString(); 40 | Mockito.doAnswer( 41 | new JavaDelegateAnswer(execution -> setVariablesForMultipleInvocations(combineVariableMaps(variableMap, values), 42 | countVariable, 43 | execution)) 44 | ).when(mock).execute(any()); 45 | } catch (final Exception e) { 46 | throw new RuntimeException(e); 47 | } 48 | } 49 | 50 | @Override 51 | public void onExecutionThrowBpmnError(final BpmnError bpmnError) { 52 | doAnswer(new JavaDelegate() { 53 | 54 | @Override 55 | public void execute(final DelegateExecution execution) throws Exception { 56 | throw bpmnError; 57 | } 58 | }); 59 | } 60 | 61 | @Override 62 | public void onExecutionThrowException(final Exception exception) { 63 | doAnswer(new JavaDelegate() { 64 | @Override 65 | public void execute(DelegateExecution execution) throws Exception { 66 | throw exception; 67 | } 68 | }); 69 | } 70 | 71 | private void doAnswer(final JavaDelegate javaDelegate) { 72 | try { 73 | Mockito.doAnswer(new JavaDelegateAnswer(javaDelegate)).when(mock).execute(any()); 74 | } catch (final Exception e) { 75 | throw new RuntimeException(e); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/mock/FluentTaskListenerMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.mock; 2 | 3 | import static org.mockito.Mockito.mock; 4 | 5 | import org.camunda.bpm.engine.delegate.BpmnError; 6 | import org.camunda.bpm.engine.delegate.DelegateTask; 7 | import org.camunda.bpm.engine.delegate.TaskListener; 8 | import org.camunda.bpm.engine.variable.VariableMap; 9 | import org.camunda.community.mockito.answer.TaskListenerAnswer; 10 | import org.mockito.Mockito; 11 | 12 | import java.util.UUID; 13 | 14 | public class FluentTaskListenerMock extends FluentMock implements TaskListener { 15 | 16 | public FluentTaskListenerMock() { 17 | super(mock(TaskListener.class), DelegateTask.class); 18 | } 19 | 20 | @Override 21 | public final void notify(final DelegateTask delegateTask) { 22 | mock.notify(delegateTask); 23 | } 24 | 25 | @Override 26 | public void onExecutionSetVariables(final VariableMap variables) { 27 | doAnswer(new TaskListener() { 28 | 29 | @Override 30 | public void notify(final DelegateTask delegateTask) { 31 | setVariables(delegateTask, variables); 32 | } 33 | }); 34 | } 35 | 36 | @Override 37 | public void onExecutionSetVariables(VariableMap variableMap, VariableMap... values) { 38 | try { 39 | final String countVariable = UUID.randomUUID().toString(); 40 | Mockito.doAnswer( 41 | new TaskListenerAnswer(task -> setVariablesForMultipleInvocations(combineVariableMaps(variableMap, values), countVariable, task)) 42 | ).when(mock).notify(any()); 43 | } catch (final Exception e) { 44 | throw new RuntimeException(e); 45 | } 46 | } 47 | 48 | @Override 49 | public void onExecutionThrowBpmnError(final BpmnError bpmnError) { 50 | doAnswer(new TaskListener() { 51 | 52 | @Override 53 | public void notify(final DelegateTask delegateTask) { 54 | throw bpmnError; 55 | } 56 | }); 57 | } 58 | 59 | @Override 60 | public void onExecutionThrowException(final Exception exception) { 61 | doAnswer(new TaskListener() { 62 | @Override 63 | public void notify(DelegateTask delegateTask) { 64 | throw new RuntimeException(exception); 65 | } 66 | }); 67 | } 68 | 69 | private void doAnswer(final TaskListener taskListener) { 70 | try { 71 | Mockito.doAnswer(new TaskListenerAnswer(taskListener)).when(mock).notify(any()); 72 | } catch (final Exception e) { 73 | throw new RuntimeException(e); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/process/CallActivityMockForSpringContext.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.process; 2 | 3 | import org.camunda.bpm.engine.delegate.JavaDelegate; 4 | import org.springframework.beans.factory.config.SingletonBeanRegistry; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.context.ConfigurableApplicationContext; 7 | 8 | /** 9 | * Implementation that registers the delegates mocks for the mocked subprocess to the gived spring bean context. 10 | */ 11 | public class CallActivityMockForSpringContext extends CallActivityMock { 12 | 13 | /** Registry where all the mocks will be placed to */ 14 | private SingletonBeanRegistry springBeanRegistry; 15 | 16 | /** 17 | * @param processId Process definition key of the subprocess to mock. This should be the value of the 'called element' attribute of the 18 | * mocked CallActivity element. 19 | * @param modelConfigurer Object that allows to customize the mock process model for the subprocess 20 | * @param springBeanRegistry Spring context to place the implementations of the activities in the mocked process to 21 | */ 22 | public CallActivityMockForSpringContext(final String processId, final MockedModelConfigurer modelConfigurer, 23 | final SingletonBeanRegistry springBeanRegistry) { 24 | super(processId, modelConfigurer); 25 | this.springBeanRegistry = springBeanRegistry; 26 | } 27 | 28 | /** 29 | * Variant with an ApplicationContext as the parameter. This is usually easier to get access to in the tests 30 | * (e.g. via autowiring). 31 | */ 32 | public CallActivityMockForSpringContext(final String processId, final MockedModelConfigurer modelConfigurer, 33 | final ApplicationContext applicationContext) { 34 | this(processId, modelConfigurer, getSingletonBeanRegistry(applicationContext)); 35 | } 36 | 37 | /** 38 | * Constructor that does not allow for customizing of the mocked subprocess model 39 | */ 40 | public CallActivityMockForSpringContext(final String processId, final SingletonBeanRegistry springBeanRegistry) { 41 | this(processId, null, springBeanRegistry); 42 | } 43 | 44 | /** 45 | * Variant with an ApplicationContext as the parameter. This is usually easier to get access to in the tests 46 | * (e.g. via autowiring). 47 | */ 48 | public CallActivityMockForSpringContext(final String processId, final ApplicationContext applicationContext) { 49 | this(processId, getSingletonBeanRegistry(applicationContext)); 50 | } 51 | 52 | private static SingletonBeanRegistry getSingletonBeanRegistry(ApplicationContext applicationContext) { 53 | if (!(applicationContext instanceof ConfigurableApplicationContext)) { 54 | throw new IllegalArgumentException("applicationContext is not an instance of ConfigurableApplicationContext"); 55 | } 56 | return ((ConfigurableApplicationContext) applicationContext).getBeanFactory(); 57 | } 58 | 59 | public SingletonBeanRegistry getSpringBeanRegistry() { 60 | return springBeanRegistry; 61 | } 62 | 63 | @Override 64 | protected void registerJavaDelegateMock(String delegateReferenceName, JavaDelegate delegate) { 65 | // Since mock delegate names are generated as random strings, we don't have to unregister an existing bean 66 | springBeanRegistry.registerSingleton(delegateReferenceName, delegate); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/AbstractQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import static org.mockito.Mockito.when; 4 | 5 | import javax.annotation.Nonnull; 6 | 7 | import java.lang.reflect.Method; 8 | import java.util.List; 9 | import java.util.function.Supplier; 10 | 11 | import org.camunda.bpm.engine.query.Query; 12 | import org.camunda.community.mockito.answer.FluentAnswer; 13 | 14 | 15 | /** 16 | * This looks more complicated than it actually is ... To easily mock the 17 | * behaviour of queries, all common functionality is extracted to this abstract 18 | * super class, the high level of Generics is needed for the fluent api pattern, 19 | * so the abstract mock implementing the generic Query interface must also keep 20 | * a reference to itself. 21 | * 22 | * @param 23 | * the type of the AbstractQueryMock (repeat the type of the class you 24 | * are building). Used to "return this" 25 | * @param 26 | * the type of the query to mock (for example: TaskQuery). 27 | * @param 28 | * the type of the expected result (for example: Execution). 29 | * @param 30 | * the type of the service the query belongs to (used for "forService" 31 | * binding), for Example: TaskService. 32 | * 33 | * @author Jan Galinski 34 | */ 35 | abstract class AbstractQueryMock, Q extends Query, R extends Object, S> implements Supplier { 36 | 37 | /** 38 | * The internally stored query instance. 39 | */ 40 | private final Q query; 41 | 42 | /** 43 | * Used for mocking the query creation via reflection. 44 | */ 45 | private final Method createMethod; 46 | 47 | /** 48 | * Creates a new query mock and mocks fluent api behavior by adding a default 49 | * answer to the mock. Every createMethod will return the mock itself, except 50 | *
    51 | *
  • list() - returns empty ArrayList
  • 52 | *
  • singeResult() - returns null
  • 53 | *
54 | * 55 | * @param queryType 56 | * the type of the query to mock. 57 | * @param serviceType 58 | * the type of service that generates this query 59 | */ 60 | protected AbstractQueryMock(@Nonnull final Class queryType, @Nonnull final Class serviceType) { 61 | query = FluentAnswer.createMock(queryType); 62 | createMethod = createMethod(queryType, serviceType); 63 | // No default values for singleResult() and list() anymore, as it is default already 64 | // and causes UnnecessaryStubbingException if list() is not used on the stub. 65 | } 66 | 67 | private Method createMethod(@Nonnull final Class queryType, @Nonnull Class serviceType) { 68 | try { 69 | return serviceType.getDeclaredMethod("create" + queryType.getSimpleName()); 70 | } catch (NoSuchMethodException e) { 71 | throw new RuntimeException(e); 72 | } 73 | } 74 | 75 | public Q list(final List result) { 76 | when(query.list()).thenReturn(result); 77 | return get(); 78 | } 79 | 80 | public Q singleResult(final R result) { 81 | when(query.singleResult()).thenReturn(result); 82 | return get(); 83 | } 84 | 85 | public Q count(long result) { 86 | when(query.count()).thenReturn(result); 87 | return get(); 88 | } 89 | 90 | public Q listPage(List result, int min, int max) { 91 | when(query.listPage(min,max)).thenReturn(result); 92 | return get(); 93 | } 94 | 95 | public M forService(S service) { 96 | try { 97 | when(createMethod.invoke(service)).thenReturn(get()); 98 | } catch (Exception e) { 99 | throw new RuntimeException(e); 100 | } 101 | return (M) this; 102 | } 103 | 104 | @Override 105 | public final Q get() { 106 | return query; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/ActivityStatisticsQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.ManagementService; 4 | import org.camunda.bpm.engine.management.ActivityStatistics; 5 | import org.camunda.bpm.engine.management.ActivityStatisticsQuery; 6 | 7 | public class ActivityStatisticsQueryMock extends AbstractQueryMock { 8 | 9 | public ActivityStatisticsQueryMock() { 10 | super(ActivityStatisticsQuery.class, ManagementService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/AuthorizationQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.AuthorizationService; 4 | import org.camunda.bpm.engine.authorization.Authorization; 5 | import org.camunda.bpm.engine.authorization.AuthorizationQuery; 6 | 7 | public class AuthorizationQueryMock extends AbstractQueryMock { 8 | 9 | public AuthorizationQueryMock() { 10 | super(AuthorizationQuery.class, AuthorizationService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/BatchQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.ManagementService; 4 | import org.camunda.bpm.engine.batch.Batch; 5 | import org.camunda.bpm.engine.batch.BatchQuery; 6 | 7 | public class BatchQueryMock extends AbstractQueryMock { 8 | 9 | public BatchQueryMock() { 10 | super(BatchQuery.class, ManagementService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/BatchStatisticsQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.ManagementService; 4 | import org.camunda.bpm.engine.batch.BatchStatistics; 5 | import org.camunda.bpm.engine.batch.BatchStatisticsQuery; 6 | 7 | public class BatchStatisticsQueryMock extends AbstractQueryMock { 8 | 9 | public BatchStatisticsQueryMock() { 10 | super(BatchStatisticsQuery.class, ManagementService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/CaseDefinitionQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.RepositoryService; 4 | import org.camunda.bpm.engine.repository.CaseDefinition; 5 | import org.camunda.bpm.engine.repository.CaseDefinitionQuery; 6 | 7 | public class CaseDefinitionQueryMock extends AbstractQueryMock { 8 | 9 | public CaseDefinitionQueryMock() { 10 | super(CaseDefinitionQuery.class, RepositoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/CaseExecutionQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.CaseService; 4 | import org.camunda.bpm.engine.runtime.CaseExecution; 5 | import org.camunda.bpm.engine.runtime.CaseExecutionQuery; 6 | 7 | public class CaseExecutionQueryMock extends AbstractQueryMock { 8 | 9 | public CaseExecutionQueryMock() { 10 | super(CaseExecutionQuery.class, CaseService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/CaseInstanceQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.CaseService; 4 | import org.camunda.bpm.engine.runtime.CaseInstance; 5 | import org.camunda.bpm.engine.runtime.CaseInstanceQuery; 6 | 7 | public class CaseInstanceQueryMock extends AbstractQueryMock { 8 | 9 | public CaseInstanceQueryMock() { 10 | super(CaseInstanceQuery.class, CaseService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/DecisionDefinitionQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.RepositoryService; 4 | import org.camunda.bpm.engine.repository.DecisionDefinition; 5 | import org.camunda.bpm.engine.repository.DecisionDefinitionQuery; 6 | 7 | public class DecisionDefinitionQueryMock extends AbstractQueryMock { 8 | 9 | public DecisionDefinitionQueryMock() { 10 | super(DecisionDefinitionQuery.class, RepositoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/DeploymentQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.RepositoryService; 4 | import org.camunda.bpm.engine.repository.Deployment; 5 | import org.camunda.bpm.engine.repository.DeploymentQuery; 6 | 7 | public class DeploymentQueryMock extends AbstractQueryMock { 8 | 9 | public DeploymentQueryMock() { 10 | super(DeploymentQuery.class, RepositoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/DeploymentStatisticsQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.ManagementService; 4 | import org.camunda.bpm.engine.management.DeploymentStatistics; 5 | import org.camunda.bpm.engine.management.DeploymentStatisticsQuery; 6 | 7 | public class DeploymentStatisticsQueryMock extends AbstractQueryMock { 8 | 9 | public DeploymentStatisticsQueryMock() { 10 | super(DeploymentStatisticsQuery.class, ManagementService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/EventSubscriptionQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.RuntimeService; 4 | import org.camunda.bpm.engine.runtime.EventSubscription; 5 | import org.camunda.bpm.engine.runtime.EventSubscriptionQuery; 6 | 7 | public class EventSubscriptionQueryMock extends AbstractQueryMock { 8 | 9 | public EventSubscriptionQueryMock() { 10 | super(EventSubscriptionQuery.class, RuntimeService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/ExecutionQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.RuntimeService; 4 | import org.camunda.bpm.engine.runtime.Execution; 5 | import org.camunda.bpm.engine.runtime.ExecutionQuery; 6 | 7 | public class ExecutionQueryMock extends AbstractQueryMock { 8 | 9 | public ExecutionQueryMock() { 10 | super(ExecutionQuery.class, RuntimeService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/ExternalTaskQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.ExternalTaskService; 4 | import org.camunda.bpm.engine.externaltask.ExternalTask; 5 | import org.camunda.bpm.engine.externaltask.ExternalTaskQuery; 6 | 7 | public class ExternalTaskQueryMock extends AbstractQueryMock { 8 | 9 | public ExternalTaskQueryMock() { 10 | super(ExternalTaskQuery.class, ExternalTaskService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/FilterQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.FilterService; 4 | import org.camunda.bpm.engine.filter.Filter; 5 | import org.camunda.bpm.engine.filter.FilterQuery; 6 | 7 | public class FilterQueryMock extends AbstractQueryMock { 8 | 9 | public FilterQueryMock() { 10 | super(FilterQuery.class, FilterService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/GroupQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.IdentityService; 4 | import org.camunda.bpm.engine.identity.Group; 5 | import org.camunda.bpm.engine.identity.GroupQuery; 6 | 7 | public class GroupQueryMock extends AbstractQueryMock { 8 | 9 | public GroupQueryMock() { 10 | super(GroupQuery.class, IdentityService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricActivityInstanceQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricActivityInstance; 5 | import org.camunda.bpm.engine.history.HistoricActivityInstanceQuery; 6 | 7 | public class HistoricActivityInstanceQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricActivityInstanceQueryMock() { 10 | super(HistoricActivityInstanceQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricActivityStatisticsQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricActivityStatistics; 5 | import org.camunda.bpm.engine.history.HistoricActivityStatisticsQuery; 6 | 7 | public class HistoricActivityStatisticsQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricActivityStatisticsQueryMock() { 10 | super(HistoricActivityStatisticsQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricBatchQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.batch.history.HistoricBatch; 5 | import org.camunda.bpm.engine.batch.history.HistoricBatchQuery; 6 | 7 | public class HistoricBatchQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricBatchQueryMock() { 10 | super(HistoricBatchQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricCaseActivityInstanceQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricCaseActivityInstance; 5 | import org.camunda.bpm.engine.history.HistoricCaseActivityInstanceQuery; 6 | 7 | public class HistoricCaseActivityInstanceQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricCaseActivityInstanceQueryMock() { 10 | super(HistoricCaseActivityInstanceQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricCaseInstanceQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricCaseInstance; 5 | import org.camunda.bpm.engine.history.HistoricCaseInstanceQuery; 6 | 7 | public class HistoricCaseInstanceQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricCaseInstanceQueryMock() { 10 | super(HistoricCaseInstanceQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricDecisionInstanceQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricDecisionInstance; 5 | import org.camunda.bpm.engine.history.HistoricDecisionInstanceQuery; 6 | 7 | public class HistoricDecisionInstanceQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricDecisionInstanceQueryMock() { 10 | super(HistoricDecisionInstanceQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricDetailQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricDetail; 5 | import org.camunda.bpm.engine.history.HistoricDetailQuery; 6 | 7 | public class HistoricDetailQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricDetailQueryMock() { 10 | super(HistoricDetailQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricIdentityLinkLogQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricIdentityLinkLog; 5 | import org.camunda.bpm.engine.history.HistoricIdentityLinkLogQuery; 6 | 7 | public class HistoricIdentityLinkLogQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricIdentityLinkLogQueryMock() { 10 | super(HistoricIdentityLinkLogQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricIncidentQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricIncident; 5 | import org.camunda.bpm.engine.history.HistoricIncidentQuery; 6 | 7 | public class HistoricIncidentQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricIncidentQueryMock() { 10 | super(HistoricIncidentQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricJobLogQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricJobLog; 5 | import org.camunda.bpm.engine.history.HistoricJobLogQuery; 6 | 7 | public class HistoricJobLogQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricJobLogQueryMock() { 10 | super(HistoricJobLogQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricProcessInstanceQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricProcessInstance; 5 | import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; 6 | 7 | public class HistoricProcessInstanceQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricProcessInstanceQueryMock() { 10 | super(HistoricProcessInstanceQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricTaskInstanceQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricTaskInstance; 5 | import org.camunda.bpm.engine.history.HistoricTaskInstanceQuery; 6 | 7 | public class HistoricTaskInstanceQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricTaskInstanceQueryMock() { 10 | super(HistoricTaskInstanceQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/HistoricVariableInstanceQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.HistoricVariableInstance; 5 | import org.camunda.bpm.engine.history.HistoricVariableInstanceQuery; 6 | 7 | public class HistoricVariableInstanceQueryMock extends AbstractQueryMock { 8 | 9 | public HistoricVariableInstanceQueryMock() { 10 | super(HistoricVariableInstanceQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/IncidentQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.RuntimeService; 4 | import org.camunda.bpm.engine.runtime.Incident; 5 | import org.camunda.bpm.engine.runtime.IncidentQuery; 6 | 7 | public class IncidentQueryMock extends AbstractQueryMock { 8 | 9 | public IncidentQueryMock() { 10 | super(IncidentQuery.class, RuntimeService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/JobDefinitionQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.ManagementService; 4 | import org.camunda.bpm.engine.management.JobDefinition; 5 | import org.camunda.bpm.engine.management.JobDefinitionQuery; 6 | 7 | public class JobDefinitionQueryMock extends AbstractQueryMock { 8 | 9 | public JobDefinitionQueryMock() { 10 | super(JobDefinitionQuery.class, ManagementService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/JobQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.ManagementService; 4 | import org.camunda.bpm.engine.runtime.Job; 5 | import org.camunda.bpm.engine.runtime.JobQuery; 6 | 7 | public class JobQueryMock extends AbstractQueryMock { 8 | 9 | public JobQueryMock() { 10 | super(JobQuery.class, ManagementService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/ProcessDefinitionQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.RepositoryService; 4 | import org.camunda.bpm.engine.repository.ProcessDefinition; 5 | import org.camunda.bpm.engine.repository.ProcessDefinitionQuery; 6 | 7 | public class ProcessDefinitionQueryMock extends AbstractQueryMock { 8 | 9 | public ProcessDefinitionQueryMock() { 10 | super(ProcessDefinitionQuery.class, RepositoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/ProcessDefinitionStatisticsQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.ManagementService; 4 | import org.camunda.bpm.engine.management.ProcessDefinitionStatistics; 5 | import org.camunda.bpm.engine.management.ProcessDefinitionStatisticsQuery; 6 | 7 | public class ProcessDefinitionStatisticsQueryMock extends AbstractQueryMock { 8 | 9 | public ProcessDefinitionStatisticsQueryMock() { 10 | super(ProcessDefinitionStatisticsQuery.class, ManagementService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/ProcessInstanceQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.RuntimeService; 4 | import org.camunda.bpm.engine.runtime.ProcessInstance; 5 | import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; 6 | 7 | public class ProcessInstanceQueryMock extends AbstractQueryMock { 8 | 9 | public ProcessInstanceQueryMock() { 10 | super(ProcessInstanceQuery.class, RuntimeService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/TaskQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.TaskService; 4 | import org.camunda.bpm.engine.task.Task; 5 | import org.camunda.bpm.engine.task.TaskQuery; 6 | 7 | public class TaskQueryMock extends AbstractQueryMock { 8 | 9 | public TaskQueryMock() { 10 | super(TaskQuery.class, TaskService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/TenantQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.IdentityService; 4 | import org.camunda.bpm.engine.identity.Tenant; 5 | import org.camunda.bpm.engine.identity.TenantQuery; 6 | 7 | public class TenantQueryMock extends AbstractQueryMock { 8 | 9 | public TenantQueryMock() { 10 | super(TenantQuery.class, IdentityService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/UserOperationLogQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.HistoryService; 4 | import org.camunda.bpm.engine.history.UserOperationLogEntry; 5 | import org.camunda.bpm.engine.history.UserOperationLogQuery; 6 | 7 | public class UserOperationLogQueryMock extends AbstractQueryMock { 8 | 9 | public UserOperationLogQueryMock() { 10 | super(UserOperationLogQuery.class, HistoryService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/UserQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.IdentityService; 4 | import org.camunda.bpm.engine.identity.User; 5 | import org.camunda.bpm.engine.identity.UserQuery; 6 | 7 | public class UserQueryMock extends AbstractQueryMock { 8 | 9 | public UserQueryMock() { 10 | super(UserQuery.class, IdentityService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/query/VariableInstanceQueryMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.RuntimeService; 4 | import org.camunda.bpm.engine.runtime.VariableInstance; 5 | import org.camunda.bpm.engine.runtime.VariableInstanceQuery; 6 | 7 | public class VariableInstanceQueryMock extends AbstractQueryMock { 8 | 9 | public VariableInstanceQueryMock() { 10 | super(VariableInstanceQuery.class, RuntimeService.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/service/CaseServiceStubBuilder.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.service; 2 | 3 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 4 | import org.camunda.bpm.engine.CaseService; 5 | import org.camunda.bpm.engine.variable.VariableMap; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.stream.Collectors; 11 | 12 | import static org.camunda.bpm.engine.variable.Variables.createVariables; 13 | import static org.mockito.ArgumentMatchers.*; 14 | import static org.mockito.Mockito.doAnswer; 15 | 16 | 17 | /** 18 | * Builder to stub the case service behavior regarding variables. 19 | */ 20 | public class CaseServiceStubBuilder { 21 | 22 | private final CaseService caseService; 23 | private final VariableMap variables; 24 | private final VariableMap localVariables; 25 | private final List> factories = new ArrayList<>(); 26 | 27 | /** 28 | * Constructs the builder. 29 | * 30 | * @param caseService case service mocked by mockito. 31 | * @param variables variables to use. 32 | * @param localVariables local variables to use. 33 | */ 34 | public CaseServiceStubBuilder(CaseService caseService, VariableMap variables, VariableMap localVariables) { 35 | this.caseService = caseService; 36 | this.variables = variables; 37 | this.localVariables = localVariables; 38 | } 39 | 40 | /** 41 | * Constructs the builder with no variables. 42 | * 43 | * @param caseService case service mocked by mockito. 44 | */ 45 | public CaseServiceStubBuilder(CaseService caseService) { 46 | this(caseService, createVariables(), createVariables()); 47 | } 48 | 49 | /** 50 | * Defines a new variable to watch for. 51 | * 52 | * @param variableFactory variable factory for the variable. 53 | * @param type of the variable. 54 | * 55 | * @return builder. 56 | */ 57 | public CaseServiceStubBuilder define(VariableFactory variableFactory) { 58 | this.factories.add(variableFactory); 59 | return this; 60 | } 61 | 62 | /** 63 | * Defines a new variable to watch for and sets initial value. 64 | * 65 | * @param variableFactory variable factory for the variable. 66 | * @param initialValue initial value. 67 | * @param type of the variable. 68 | * 69 | * @return builder. 70 | */ 71 | public CaseServiceStubBuilder defineAndInitialize(VariableFactory variableFactory, T initialValue) { 72 | define(variableFactory); 73 | variableFactory.on(variables).set(initialValue); 74 | return this; 75 | } 76 | 77 | /** 78 | * Defines a new variable to watch for and sets initial value to local variable. 79 | * 80 | * @param variableFactory variable factory for the variable. 81 | * @param initialValue initial value. 82 | * @param type of the variable. 83 | * 84 | * @return builder. 85 | */ 86 | public CaseServiceStubBuilder defineAndInitializeLocal(VariableFactory variableFactory, T initialValue) { 87 | define(variableFactory); 88 | variableFactory.on(localVariables).set(initialValue); 89 | return this; 90 | } 91 | 92 | /** 93 | * Builds the stubs, configuring the mockito behavior on specified case service mock. 94 | */ 95 | public CaseService build() { 96 | 97 | factories.forEach((factory) -> { 98 | // getVariable(String, String), setVariable(String, String, Object), getVariables(), getVariables(List) 99 | doAnswer((invocation) -> factory.from(variables).get()).when(caseService).getVariable(anyString(), eq(factory.getName())); 100 | doAnswer((invocation) -> variables.put(factory.getName(), invocation.getArguments()[2])).when(caseService).setVariable(anyString(), eq(factory.getName()), any()); 101 | doAnswer((invocation) -> variables).when(caseService).getVariables(anyString()); 102 | doAnswer((invocation) -> { 103 | @SuppressWarnings("unchecked") final List requestedVariableNames = (List) invocation.getArguments()[1]; // [0]: id, [1]: list of vars 104 | return variables.entrySet().stream().filter((variable) -> requestedVariableNames.contains(variable.getKey())).map(Map.Entry::getValue).collect(Collectors.toList()); 105 | }).when(caseService).getVariables(anyString(), anyList()); 106 | 107 | // getVariableLocal(String, String), setVariableLocal(String, String, Object), getVariablesLocal(), getVariablesLocal(List) 108 | doAnswer((invocation) -> factory.from(localVariables).get()).when(caseService).getVariableLocal(anyString(), eq(factory.getName())); 109 | doAnswer((invocation) -> localVariables.put(factory.getName(), invocation.getArguments()[2])).when(caseService) 110 | .setVariableLocal(anyString(), eq(factory.getName()), any()); 111 | doAnswer((invocation) -> localVariables).when(caseService).getVariablesLocal(anyString()); 112 | doAnswer((invocation) -> { 113 | @SuppressWarnings("unchecked") final List requestedVariableNames = (List) invocation.getArguments()[1]; // [0]: id, [1]: list of vars 114 | return localVariables.entrySet().stream().filter((variable) -> requestedVariableNames.contains(variable.getKey())).map(Map.Entry::getValue).collect(Collectors.toList()); 115 | }).when(caseService).getVariablesLocal(anyString(), anyList()); 116 | }); 117 | 118 | return this.caseService; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/service/RuntimeServiceFluentMock.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.service; 2 | 3 | import org.camunda.bpm.engine.RuntimeService; 4 | import org.camunda.bpm.engine.variable.VariableMap; 5 | import org.camunda.bpm.engine.variable.value.TypedValue; 6 | 7 | import java.util.Collection; 8 | import java.util.Map; 9 | 10 | import static org.mockito.ArgumentMatchers.anyString; 11 | import static org.mockito.ArgumentMatchers.eq; 12 | import static org.mockito.Mockito.mock; 13 | import static org.mockito.Mockito.when; 14 | 15 | @SuppressWarnings("unused") 16 | public class RuntimeServiceFluentMock { 17 | 18 | private final RuntimeService runtimeService; 19 | 20 | /** 21 | * Create fluent mock instance and constructs the runtime service mock. 22 | */ 23 | public RuntimeServiceFluentMock() { 24 | this.runtimeService = mock(RuntimeService.class); 25 | } 26 | 27 | public RuntimeServiceFluentMock(RuntimeService runtimeService) { 28 | this.runtimeService = runtimeService; 29 | } 30 | 31 | public RuntimeServiceFluentMock getVariable(final String variableName, final Object value, final Object... values) { 32 | when(runtimeService.getVariable(anyString(), eq(variableName))).thenReturn(value, values); 33 | return this; 34 | } 35 | 36 | public RuntimeServiceFluentMock getVariables(final Map values) { 37 | when(runtimeService.getVariables(anyString())).thenReturn(values); 38 | return this; 39 | } 40 | 41 | public RuntimeServiceFluentMock getVariables(final Collection variableNames, final Map values) { 42 | when(runtimeService.getVariables(anyString(), eq(variableNames))).thenReturn(values); 43 | return this; 44 | } 45 | 46 | public RuntimeServiceFluentMock getVariableLocal(final String variableName, final Object value, final Object... values) { 47 | when(runtimeService.getVariableLocal(anyString(), eq(variableName))).thenReturn(value, values); 48 | return this; 49 | } 50 | 51 | public RuntimeServiceFluentMock getVariablesLocal(final Map values) { 52 | when(runtimeService.getVariablesLocal(anyString())).thenReturn(values); 53 | return this; 54 | } 55 | 56 | public RuntimeServiceFluentMock getVariablesLocal(final Collection variableNames, final Map values) { 57 | when(runtimeService.getVariablesLocal(anyString(), eq(variableNames))).thenReturn(values); 58 | return this; 59 | } 60 | 61 | public RuntimeServiceFluentMock getVariableLocalTyped(final String variableName, boolean deserializeValues, final T value, final T... values) { 62 | when(runtimeService.getVariableLocalTyped(anyString(), eq(variableName), eq(deserializeValues))).thenReturn(value, values); 63 | return this; 64 | } 65 | 66 | public RuntimeServiceFluentMock getVariablesLocalTyped(boolean deserializeValues, final VariableMap values) { 67 | when(runtimeService.getVariablesLocalTyped(anyString(), eq(deserializeValues))).thenReturn(values); 68 | return this; 69 | } 70 | 71 | public RuntimeServiceFluentMock getVariablesLocalTyped(final Collection variableNames, boolean deserializeValues, final VariableMap values) { 72 | when(runtimeService.getVariablesLocalTyped(anyString(), eq(variableNames), eq(deserializeValues))).thenReturn(values); 73 | return this; 74 | } 75 | 76 | public RuntimeServiceFluentMock getVariableLocalTyped(final String variableName, final T value, final T... values) { 77 | when(runtimeService.getVariableLocalTyped(anyString(), eq(variableName))).thenReturn(value, values); 78 | return this; 79 | } 80 | 81 | public RuntimeServiceFluentMock getVariablesLocalTyped(final VariableMap values) { 82 | when(runtimeService.getVariablesLocalTyped(anyString())).thenReturn(values); 83 | return this; 84 | } 85 | 86 | public RuntimeServiceFluentMock getVariableTyped(final String variableName, boolean deserializeValues, final T value, final T... values) { 87 | when(runtimeService.getVariableTyped(anyString(), eq(variableName), eq(deserializeValues))).thenReturn(value, values); 88 | return this; 89 | } 90 | 91 | public RuntimeServiceFluentMock getVariablesTyped(boolean deserializeValues, final VariableMap values) { 92 | when(runtimeService.getVariablesTyped(anyString(), eq(deserializeValues))).thenReturn(values); 93 | return this; 94 | } 95 | 96 | public RuntimeServiceFluentMock getVariablesTyped(final Collection variableNames, boolean deserializeValues, final VariableMap values) { 97 | when(runtimeService.getVariablesTyped(anyString(), eq(variableNames), eq(deserializeValues))).thenReturn(values); 98 | return this; 99 | } 100 | 101 | public RuntimeServiceFluentMock getVariableTyped(final String variableName, final T value, final T... values) { 102 | when(runtimeService.getVariableTyped(anyString(), eq(variableName))).thenReturn(value, values); 103 | return this; 104 | } 105 | 106 | public RuntimeServiceFluentMock getVariablesTyped(final VariableMap values) { 107 | when(runtimeService.getVariablesTyped(anyString())).thenReturn(values); 108 | return this; 109 | } 110 | 111 | public RuntimeService getRuntimeService() { 112 | return runtimeService; 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/service/RuntimeServiceStubBuilder.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.service; 2 | 3 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 4 | import org.camunda.bpm.engine.RuntimeService; 5 | import org.camunda.bpm.engine.variable.VariableMap; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.stream.Collectors; 11 | 12 | import static org.camunda.bpm.engine.variable.Variables.createVariables; 13 | import static org.mockito.ArgumentMatchers.*; 14 | import static org.mockito.Mockito.doAnswer; 15 | 16 | 17 | /** 18 | * Builder to stub the runtime service behavior regarding variables. 19 | */ 20 | public class RuntimeServiceStubBuilder { 21 | 22 | private final RuntimeService runtimeService; 23 | private final VariableMap variables; 24 | private final VariableMap localVariables; 25 | private final List> factories = new ArrayList<>(); 26 | 27 | /** 28 | * Constructs the builder. 29 | * 30 | * @param runtimeService runtime service mocked by mockito. 31 | * @param variables variables to use. 32 | * @param localVariables local variables to use. 33 | */ 34 | public RuntimeServiceStubBuilder(RuntimeService runtimeService, VariableMap variables, VariableMap localVariables) { 35 | this.runtimeService = runtimeService; 36 | this.variables = variables; 37 | this.localVariables = localVariables; 38 | } 39 | 40 | /** 41 | * Constructs the builder with no variables. 42 | * 43 | * @param runtimeService runtime service mocked by mockito. 44 | */ 45 | public RuntimeServiceStubBuilder(RuntimeService runtimeService) { 46 | this(runtimeService, createVariables(), createVariables()); 47 | } 48 | 49 | /** 50 | * Defines a new variable to watch for. 51 | * 52 | * @param variableFactory variable factory for the variable. 53 | * @param type of the variable. 54 | * 55 | * @return builder. 56 | */ 57 | public RuntimeServiceStubBuilder define(VariableFactory variableFactory) { 58 | this.factories.add(variableFactory); 59 | return this; 60 | } 61 | 62 | /** 63 | * Defines a new variable to watch for and sets initial value. 64 | * 65 | * @param variableFactory variable factory for the variable. 66 | * @param initialValue initial value. 67 | * @param type of the variable. 68 | * 69 | * @return builder. 70 | */ 71 | public RuntimeServiceStubBuilder defineAndInitialize(VariableFactory variableFactory, T initialValue) { 72 | define(variableFactory); 73 | variableFactory.on(variables).set(initialValue); 74 | return this; 75 | } 76 | 77 | /** 78 | * Defines a new variable to watch for and sets initial value to local variable. 79 | * 80 | * @param variableFactory variable factory for the variable. 81 | * @param initialValue initial value. 82 | * @param type of the variable. 83 | * 84 | * @return builder. 85 | */ 86 | public RuntimeServiceStubBuilder defineAndInitializeLocal(VariableFactory variableFactory, T initialValue) { 87 | define(variableFactory); 88 | variableFactory.on(localVariables).set(initialValue); 89 | return this; 90 | } 91 | 92 | /** 93 | * Builds the stubs, configuring the mockito behavior on specified runtime service mock. 94 | */ 95 | public RuntimeService build() { 96 | 97 | factories.forEach((factory) -> { 98 | // getVariable(String, String), setVariable(String, String, Object), getVariables(), getVariables(List) 99 | doAnswer((invocation) -> factory.from(variables).get()).when(runtimeService).getVariable(anyString(), eq(factory.getName())); 100 | doAnswer((invocation) -> variables.put(factory.getName(), invocation.getArguments()[2])).when(runtimeService).setVariable(anyString(), eq(factory.getName()), any()); 101 | doAnswer((invocation) -> variables).when(runtimeService).getVariables(anyString()); 102 | doAnswer((invocation) -> { 103 | @SuppressWarnings("unchecked") final List requestedVariableNames = (List) invocation.getArguments()[1]; // [0]: id, [1]: list of vars 104 | return variables.entrySet().stream().filter((variable) -> requestedVariableNames.contains(variable.getKey())).map(Map.Entry::getValue).collect(Collectors.toList()); 105 | }).when(runtimeService).getVariables(anyString(), anyList()); 106 | 107 | // getVariableLocal(String, String), setVariableLocal(String, String, Object), getVariablesLocal(), getVariablesLocal(List) 108 | doAnswer((invocation) -> factory.from(localVariables).get()).when(runtimeService).getVariableLocal(anyString(), eq(factory.getName())); 109 | doAnswer((invocation) -> localVariables.put(factory.getName(), invocation.getArguments()[2])).when(runtimeService) 110 | .setVariableLocal(anyString(), eq(factory.getName()), any()); 111 | doAnswer((invocation) -> localVariables).when(runtimeService).getVariablesLocal(anyString()); 112 | doAnswer((invocation) -> { 113 | @SuppressWarnings("unchecked") final List requestedVariableNames = (List) invocation.getArguments()[1]; // [0]: id, [1]: list of vars 114 | return localVariables.entrySet().stream().filter((variable) -> requestedVariableNames.contains(variable.getKey())).map(Map.Entry::getValue).collect(Collectors.toList()); 115 | }).when(runtimeService).getVariablesLocal(anyString(), anyList()); 116 | }); 117 | 118 | return this.runtimeService; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/service/TaskServiceStubBuilder.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.service; 2 | 3 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 4 | import org.camunda.bpm.engine.RuntimeService; 5 | import org.camunda.bpm.engine.TaskService; 6 | import org.camunda.bpm.engine.variable.VariableMap; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.stream.Collectors; 12 | 13 | import static org.camunda.bpm.engine.variable.Variables.createVariables; 14 | import static org.mockito.ArgumentMatchers.*; 15 | import static org.mockito.Mockito.doAnswer; 16 | 17 | 18 | /** 19 | * Builder to stub the task service behavior regarding variables. 20 | */ 21 | public class TaskServiceStubBuilder { 22 | 23 | private final TaskService taskService; 24 | private final VariableMap variables; 25 | private final VariableMap localVariables; 26 | private final List> factories = new ArrayList<>(); 27 | 28 | /** 29 | * Constructs the builder. 30 | * 31 | * @param taskService task service mocked by mockito. 32 | * @param variables variables to use. 33 | * @param localVariables local variables to use. 34 | */ 35 | public TaskServiceStubBuilder(TaskService taskService, VariableMap variables, VariableMap localVariables) { 36 | this.taskService = taskService; 37 | this.variables = variables; 38 | this.localVariables = localVariables; 39 | } 40 | 41 | /** 42 | * Constructs the builder with no variables. 43 | * 44 | * @param taskService task service mocked by mockito. 45 | */ 46 | public TaskServiceStubBuilder(TaskService taskService) { 47 | this(taskService, createVariables(), createVariables()); 48 | } 49 | 50 | /** 51 | * Defines a new variable to watch for. 52 | * 53 | * @param variableFactory variable factory for the variable. 54 | * @param type of the variable. 55 | * 56 | * @return builder. 57 | */ 58 | public TaskServiceStubBuilder define(VariableFactory variableFactory) { 59 | this.factories.add(variableFactory); 60 | return this; 61 | } 62 | 63 | /** 64 | * Defines a new variable to watch for and sets initial value. 65 | * 66 | * @param variableFactory variable factory for the variable. 67 | * @param initialValue initial value. 68 | * @param type of the variable. 69 | * 70 | * @return builder. 71 | */ 72 | public TaskServiceStubBuilder defineAndInitialize(VariableFactory variableFactory, T initialValue) { 73 | define(variableFactory); 74 | variableFactory.on(variables).set(initialValue); 75 | return this; 76 | } 77 | 78 | /** 79 | * Defines a new variable to watch for and sets initial value to local variable. 80 | * 81 | * @param variableFactory variable factory for the variable. 82 | * @param initialValue initial value. 83 | * @param type of the variable. 84 | * 85 | * @return builder. 86 | */ 87 | public TaskServiceStubBuilder defineAndInitializeLocal(VariableFactory variableFactory, T initialValue) { 88 | define(variableFactory); 89 | variableFactory.on(localVariables).set(initialValue); 90 | return this; 91 | } 92 | 93 | /** 94 | * Builds the stubs, configuring the mockito behavior on specified task service mock. 95 | */ 96 | public TaskService build() { 97 | 98 | factories.forEach((factory) -> { 99 | // getVariable(String, String), setVariable(String, String, Object), getVariables(), getVariables(List) 100 | doAnswer((invocation) -> factory.from(variables).get()).when(taskService).getVariable(anyString(), eq(factory.getName())); 101 | doAnswer((invocation) -> variables.put(factory.getName(), invocation.getArguments()[2])).when(taskService).setVariable(anyString(), eq(factory.getName()), any()); 102 | doAnswer((invocation) -> variables).when(taskService).getVariables(anyString()); 103 | doAnswer((invocation) -> { 104 | @SuppressWarnings("unchecked") final List requestedVariableNames = (List) invocation.getArguments()[1]; // [0]: id, [1]: list of vars 105 | return variables.entrySet().stream().filter((variable) -> requestedVariableNames.contains(variable.getKey())).map(Map.Entry::getValue).collect(Collectors.toList()); 106 | }).when(taskService).getVariables(anyString(), anyList()); 107 | 108 | // getVariableLocal(String, String), setVariableLocal(String, String, Object), getVariablesLocal(), getVariablesLocal(List) 109 | doAnswer((invocation) -> factory.from(localVariables).get()).when(taskService).getVariableLocal(anyString(), eq(factory.getName())); 110 | doAnswer((invocation) -> localVariables.put(factory.getName(), invocation.getArguments()[2])).when(taskService) 111 | .setVariableLocal(anyString(), eq(factory.getName()), any()); 112 | doAnswer((invocation) -> localVariables).when(taskService).getVariablesLocal(anyString()); 113 | doAnswer((invocation) -> { 114 | @SuppressWarnings("unchecked") final List requestedVariableNames = (List) invocation.getArguments()[1]; // [0]: id, [1]: list of vars 115 | return localVariables.entrySet().stream().filter((variable) -> requestedVariableNames.contains(variable.getKey())).map(Map.Entry::getValue).collect(Collectors.toList()); 116 | }).when(taskService).getVariablesLocal(anyString(), anyList()); 117 | }); 118 | 119 | return this.taskService; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/typedvalues/VariableContextFake.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.typedvalues; 2 | 3 | import org.camunda.bpm.engine.variable.VariableMap; 4 | import org.camunda.bpm.engine.variable.Variables; 5 | import org.camunda.bpm.engine.variable.context.VariableContext; 6 | import org.camunda.bpm.engine.variable.value.TypedValue; 7 | 8 | import java.util.Set; 9 | import java.util.function.Supplier; 10 | 11 | /** 12 | * Implementation of {@link VariableContext} that internally uses a {@link VariableMap} to keep key/value pairs. 13 | *

14 | * Use {@link VariableContextFake#add(String, TypedValue)} for fluent building. 15 | */ 16 | public class VariableContextFake implements VariableContext, Supplier { 17 | 18 | private final VariableMap typedValues = Variables.createVariables(); 19 | 20 | @Override 21 | public TypedValue resolve(final String key) { 22 | return typedValues.getValueTyped(key); 23 | } 24 | 25 | @Override 26 | public boolean containsVariable(final String key) { 27 | return typedValues.containsKey(key); 28 | } 29 | 30 | @Override 31 | public Set keySet() { 32 | return typedValues.keySet(); 33 | } 34 | 35 | public VariableContextFake add(String key, TypedValue value) { 36 | typedValues.put(key, value); 37 | return this; 38 | } 39 | 40 | @Override 41 | public VariableMap get() { 42 | return typedValues; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/verify/AbstractMockitoVerification.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.verify; 2 | 3 | import static org.mockito.Mockito.never; 4 | 5 | import org.mockito.ArgumentCaptor; 6 | import org.mockito.Mockito; 7 | import org.mockito.verification.VerificationMode; 8 | 9 | /** 10 | * Base implementation of {@link MockitoVerification}. 11 | * 12 | * @param 13 | * type of the mock Delegate 14 | * @param

15 | * type of the simple argument the verified method takes 16 | */ 17 | public abstract class AbstractMockitoVerification implements MockitoVerification

{ 18 | 19 | protected final M mock; 20 | protected final ArgumentCaptor

argumentCaptor; 21 | 22 | /** 23 | * Create new instance. 24 | * 25 | * @param mock 26 | * the wrapped mock (has to be either 27 | * {@link org.camunda.bpm.engine.delegate.JavaDelegate}, 28 | * {@link org.camunda.bpm.engine.delegate.TaskListener} or 29 | * {@link org.camunda.bpm.engine.delegate.ExecutionListener}. 30 | * @param parameterType 31 | * the parameter the main method (execute() or notify() expects, one 32 | * of either 33 | * {@link org.camunda.bpm.engine.delegate.DelegateExecution} or 34 | * {@link org.camunda.bpm.engine.delegate.DelegateTask}. 35 | */ 36 | public AbstractMockitoVerification(final M mock, final Class

parameterType) { 37 | this.mock = mock; 38 | this.argumentCaptor = ArgumentCaptor.forClass(parameterType); 39 | } 40 | 41 | @Override 42 | public final ArgumentCaptor

executed() { 43 | return this.executed(Mockito.times(1)); 44 | } 45 | 46 | @Override 47 | public final ArgumentCaptor

executed(final VerificationMode verificationMode) { 48 | try { 49 | doVerify(verificationMode); 50 | } catch (final Exception e) { 51 | throw new RuntimeException(e); 52 | } 53 | return argumentCaptor; 54 | } 55 | 56 | @Override 57 | public ArgumentCaptor

executedNever() { 58 | return executed(never()); 59 | } 60 | 61 | /** 62 | * The concrete implementation must implement the method call 63 | * (verify(mock).METHOD_CALL(argumentCaptor.capture)). 64 | * 65 | * @param verificationMode 66 | * defaults to times(1), but any 67 | * {@link org.mockito.verification.VerificationMode} can be used. 68 | * @throws Exception 69 | * just in case the METHOD_CALL throws an exception. If caught, it 70 | * is propagated unchecked. 71 | */ 72 | protected abstract void doVerify(VerificationMode verificationMode) throws Exception; 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/verify/ExecutionListenerVerification.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.verify; 2 | 3 | import static org.mockito.Mockito.verify; 4 | 5 | import org.camunda.bpm.engine.delegate.DelegateExecution; 6 | import org.camunda.bpm.engine.delegate.ExecutionListener; 7 | import org.mockito.verification.VerificationMode; 8 | 9 | public class ExecutionListenerVerification extends AbstractMockitoVerification { 10 | 11 | public ExecutionListenerVerification(final ExecutionListener mock) { 12 | super(mock, DelegateExecution.class); 13 | } 14 | 15 | @Override 16 | protected void doVerify(final VerificationMode verificationMode) throws Exception { 17 | verify(mock, verificationMode).notify(argumentCaptor.capture()); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/verify/JavaDelegateVerification.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.verify; 2 | 3 | import static org.mockito.Mockito.verify; 4 | 5 | import org.camunda.bpm.engine.delegate.DelegateExecution; 6 | import org.camunda.bpm.engine.delegate.JavaDelegate; 7 | import org.mockito.verification.VerificationMode; 8 | 9 | public class JavaDelegateVerification extends AbstractMockitoVerification { 10 | 11 | public JavaDelegateVerification(final JavaDelegate mock) { 12 | super(mock, DelegateExecution.class); 13 | } 14 | 15 | @Override 16 | protected void doVerify(final VerificationMode verificationMode) throws Exception { 17 | verify(mock, verificationMode).execute(argumentCaptor.capture()); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/verify/MockitoVerification.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.verify; 2 | 3 | import org.mockito.ArgumentCaptor; 4 | import org.mockito.verification.VerificationMode; 5 | 6 | public interface MockitoVerification

{ 7 | 8 | ArgumentCaptor

executed(); 9 | 10 | ArgumentCaptor

executedNever(); 11 | 12 | ArgumentCaptor

executed(VerificationMode verificationMode); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/camunda/community/mockito/verify/TaskListenerVerification.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.verify; 2 | 3 | import static org.mockito.Mockito.verify; 4 | 5 | import org.camunda.bpm.engine.delegate.DelegateTask; 6 | import org.camunda.bpm.engine.delegate.TaskListener; 7 | import org.mockito.verification.VerificationMode; 8 | 9 | public class TaskListenerVerification extends AbstractMockitoVerification { 10 | 11 | public TaskListenerVerification(final TaskListener mock) { 12 | super(mock, DelegateTask.class); 13 | } 14 | 15 | @Override 16 | protected void doVerify(final VerificationMode verificationMode) throws Exception { 17 | verify(mock, verificationMode).notify(argumentCaptor.capture()); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/AutoMockProcessTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.camunda.community.mockito.DelegateExpressions.autoMock; 5 | import static org.camunda.community.mockito.DelegateExpressions.verifyExecutionListenerMock; 6 | import static org.camunda.community.mockito.DelegateExpressions.verifyJavaDelegateMock; 7 | import static org.camunda.community.mockito.DelegateExpressions.verifyTaskListenerMock; 8 | import static org.camunda.community.mockito.MostUsefulProcessEngineConfiguration.mostUsefulProcessEngineConfiguration; 9 | 10 | import org.camunda.bpm.engine.TaskService; 11 | import org.camunda.bpm.engine.runtime.ProcessInstance; 12 | import org.camunda.bpm.engine.test.Deployment; 13 | import org.camunda.bpm.engine.test.ProcessEngineRule; 14 | import org.camunda.bpm.engine.test.mock.Mocks; 15 | import org.junit.Before; 16 | import org.junit.Rule; 17 | import org.junit.Test; 18 | 19 | /** 20 | * If everything works as expected, the process can be deployed and executed 21 | * without explicitly registering mocks for the delegate, the execution- and the 22 | * task-listener. 23 | * 24 | * @author Jan Galinski, Holisticon AG 25 | */ 26 | public class AutoMockProcessTest { 27 | 28 | @Rule 29 | public final ProcessEngineRule processEngineRule = new ProcessEngineRule(mostUsefulProcessEngineConfiguration().buildProcessEngine()); 30 | 31 | private TaskService taskService; 32 | 33 | @Before 34 | public void setUp() { 35 | taskService = processEngineRule.getTaskService(); 36 | } 37 | 38 | @Test 39 | @Deployment(resources = "MockProcess.bpmn") 40 | public void register_mocks_for_all_listeners_and_delegates() throws Exception { 41 | autoMock("MockProcess.bpmn"); 42 | 43 | assertThat(Mocks.get("loadData")).isNotNull(); 44 | assertThat(Mocks.get("saveData")).isNotNull(); 45 | 46 | final ProcessInstance processInstance = processEngineRule.getRuntimeService().startProcessInstanceByKey("process_mock_dummy"); 47 | 48 | assertThat(processEngineRule.getTaskService().createTaskQuery().processInstanceId(processInstance.getId()).singleResult()).isNotNull(); 49 | 50 | completeTask(); 51 | 52 | verifyMocks(); 53 | } 54 | 55 | @Test 56 | @Deployment(resources = "MockProcess_withoutNS.bpmn") 57 | public void register_mocks_for_all_listeners_and_delegates_noNS() throws Exception { 58 | autoMock("MockProcess_withoutNS.bpmn"); 59 | 60 | assertThat(Mocks.get("loadData")).isNotNull(); 61 | assertThat(Mocks.get("saveData")).isNotNull(); 62 | 63 | final ProcessInstance processInstance = processEngineRule.getRuntimeService().startProcessInstanceByKey("process_mock_dummy"); 64 | 65 | assertThat(processEngineRule.getTaskService().createTaskQuery().processInstanceId(processInstance.getId()).singleResult()).isNotNull(); 66 | 67 | completeTask(); 68 | 69 | verifyMocks(); 70 | } 71 | 72 | private void verifyMocks() { 73 | verifyTaskListenerMock("verifyData").executed(); 74 | verifyExecutionListenerMock("startProcess").executed(); 75 | verifyJavaDelegateMock("loadData").executed(); 76 | verifyJavaDelegateMock("saveData").executed(); 77 | verifyExecutionListenerMock("beforeLoadData").executed(); 78 | } 79 | 80 | private void completeTask() { 81 | taskService.complete(taskService.createTaskQuery().singleResult().getId()); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/CallActivityMockBindingDeploymentTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito; 2 | 3 | import org.camunda.bpm.engine.repository.DeploymentBuilder; 4 | import org.camunda.bpm.engine.runtime.ProcessInstance; 5 | import org.camunda.bpm.engine.test.ProcessEngineRule; 6 | import org.camunda.community.mockito.process.CallActivityMock; 7 | import org.junit.Before; 8 | import org.junit.Rule; 9 | import org.junit.Test; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | import static org.camunda.community.mockito.MostUsefulProcessEngineConfiguration.mostUsefulProcessEngineConfiguration; 13 | 14 | public class CallActivityMockBindingDeploymentTest { 15 | 16 | public static final String KEY = "process_with_callActivity_binding_deployment"; 17 | public static final String KEY_MOCK = "do_stuff_mock"; 18 | 19 | @Rule 20 | public final ProcessEngineRule camunda = new ProcessEngineRule(mostUsefulProcessEngineConfiguration().buildProcessEngine()); 21 | 22 | @Before 23 | public void setUp() { 24 | DeploymentBuilder deploymentBuilder = camunda.getRepositoryService().createDeployment(); 25 | deploymentBuilder.addClasspathResource("process_with_callActivity_binding_deployment.bpmn"); 26 | CallActivityMock mock = CamundaMockito.registerCallActivityMock(KEY_MOCK).onExecutionAddVariable("foo", "bar"); 27 | mock.addToDeployment(deploymentBuilder); 28 | 29 | camunda.manageDeployment(deploymentBuilder.deploy()); 30 | } 31 | 32 | @Test 33 | public void mock_runs_with_binding_deployment() { 34 | ProcessInstance processInstance = camunda.getRuntimeService().startProcessInstanceByKey(KEY); 35 | 36 | // instance waits in endEvent 37 | ProcessInstance found = camunda.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstance.getId()) 38 | .activityIdIn("endEvent") 39 | .singleResult(); 40 | assertThat(found).isNotNull(); 41 | 42 | // subProcess set variable foo 43 | assertThat(camunda.getRuntimeService().getVariable(found.getProcessInstanceId(), "foo")).isEqualTo("bar"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/ManualMockProcessTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito; 2 | 3 | import static org.camunda.bpm.engine.variable.Variables.createVariables; 4 | import static org.camunda.community.mockito.DelegateExpressions.getExecutionListenerMock; 5 | import static org.camunda.community.mockito.DelegateExpressions.getJavaDelegateMock; 6 | import static org.camunda.community.mockito.DelegateExpressions.getTaskListenerMock; 7 | import static org.camunda.community.mockito.DelegateExpressions.registerExecutionListenerMock; 8 | import static org.camunda.community.mockito.DelegateExpressions.registerJavaDelegateMock; 9 | import static org.camunda.community.mockito.DelegateExpressions.registerTaskListenerMock; 10 | import static org.camunda.community.mockito.DelegateExpressions.verifyExecutionListenerMock; 11 | import static org.camunda.community.mockito.DelegateExpressions.verifyJavaDelegateMock; 12 | import static org.camunda.community.mockito.DelegateExpressions.verifyTaskListenerMock; 13 | import static org.camunda.community.mockito.MostUsefulProcessEngineConfiguration.mostUsefulProcessEngineConfiguration; 14 | import static org.junit.Assert.assertThat; 15 | 16 | import org.camunda.bpm.engine.ProcessEngineConfiguration; 17 | import org.camunda.bpm.engine.runtime.ProcessInstance; 18 | import org.camunda.bpm.engine.test.Deployment; 19 | import org.camunda.bpm.engine.test.ProcessEngineRule; 20 | import org.camunda.community.mockito.mock.FluentJavaDelegateMock; 21 | import org.hamcrest.CoreMatchers; 22 | import org.junit.Rule; 23 | import org.junit.Test; 24 | 25 | /** 26 | * @author Jan Galinski, Holisticon AG 27 | */ 28 | public class ManualMockProcessTest { 29 | 30 | private final ProcessEngineConfiguration configuration = mostUsefulProcessEngineConfiguration(); 31 | 32 | @Rule 33 | public final ProcessEngineRule processEngineRule = new ProcessEngineRule(mostUsefulProcessEngineConfiguration().buildProcessEngine()); 34 | 35 | @Test 36 | @Deployment(resources = "MockProcess.bpmn") 37 | public void deploy_and_run_process_with_manually_registered_mocks() { 38 | registerExecutionListenerMock("startProcess"); 39 | final FluentJavaDelegateMock loadData = registerJavaDelegateMock("loadData"); 40 | registerTaskListenerMock("verifyData").onExecutionSetVariables(createVariables().putValue("foo", "bar")); 41 | registerExecutionListenerMock("beforeLoadData"); 42 | 43 | final ProcessInstance processInstance = processEngineRule.getRuntimeService().startProcessInstanceByKey("process_mock_dummy"); 44 | 45 | assertThat(processEngineRule.getTaskService().createTaskQuery().processInstanceId(processInstance.getId()).singleResult(), CoreMatchers.notNullValue()); 46 | 47 | assertThat((String) processEngineRule.getRuntimeService().getVariable(processInstance.getId(), "foo"), CoreMatchers.is("bar")); 48 | 49 | verifyJavaDelegateMock(loadData).executed(); 50 | verifyExecutionListenerMock("startProcess").executed(); 51 | verifyTaskListenerMock("verifyData").executed(); 52 | 53 | // See if we can get the registered instances and modify their behavior. 54 | getJavaDelegateMock("loadData").onExecutionThrowBpmnError("error"); 55 | getTaskListenerMock("verifyData").onExecutionThrowBpmnError("error"); 56 | getExecutionListenerMock("startProcess").onExecutionThrowBpmnError("error"); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/MessageCorrelationMockExample.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito; 2 | 3 | import org.camunda.bpm.engine.RuntimeService; 4 | import org.camunda.bpm.engine.runtime.MessageCorrelationBuilder; 5 | import org.junit.Test; 6 | 7 | import static org.mockito.Mockito.*; 8 | 9 | public class MessageCorrelationMockExample { 10 | 11 | 12 | @Test 13 | public void mock_messageCorrelation() { 14 | 15 | // setup mock 16 | final RuntimeService runtimeService = mock(RuntimeService.class); 17 | final MessageCorrelationBuilder correlation = ProcessExpressions.mockMessageCorrelation(runtimeService, "MESSAGE_NAME"); 18 | final MyCorrelator serviceUnderTest = new MyCorrelator(runtimeService, "my-business-key", "value-1"); 19 | 20 | // execute correlation, e.g. in a class under test (service, delegate, whatever) 21 | serviceUnderTest.correlate(); 22 | 23 | // verify 24 | verify(correlation).correlate(); 25 | verify(correlation).processDefinitionId("some_process_id"); 26 | verify(correlation).processInstanceBusinessKey("my-business-key"); 27 | verify(correlation).setVariable("myVar1", "value-1"); 28 | 29 | verify(runtimeService).createMessageCorrelation("MESSAGE_NAME"); 30 | 31 | verifyNoMoreInteractions(correlation); 32 | verifyNoMoreInteractions(runtimeService); 33 | } 34 | 35 | static class MyCorrelator { 36 | 37 | private final RuntimeService runtimeService; 38 | private final String value; 39 | private final String businessKey; 40 | 41 | MyCorrelator(RuntimeService runtimeService, String businessKey, String value) { 42 | this.runtimeService = runtimeService; 43 | this.value = value; 44 | this.businessKey = businessKey; 45 | } 46 | 47 | void correlate() { 48 | this.runtimeService 49 | .createMessageCorrelation("MESSAGE_NAME") 50 | .processDefinitionId("some_process_id") 51 | .processInstanceBusinessKey(businessKey) 52 | .setVariable("myVar1", value) 53 | .correlate(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/MostUsefulProcessEngineConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito; 2 | 3 | 4 | import org.camunda.bpm.engine.ProcessEngineConfiguration; 5 | import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseListener; 6 | import org.camunda.bpm.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration; 7 | import org.camunda.bpm.engine.impl.jobexecutor.JobHandler; 8 | import org.camunda.bpm.engine.test.mock.MockExpressionManager; 9 | 10 | import java.util.ArrayList; 11 | import java.util.Objects; 12 | import java.util.function.Supplier; 13 | 14 | 15 | /** 16 | * Configuration that makes the standard camunda.cfg.xml obsolete by setting the 17 | * history, schema and job-executor settings. 18 | * 19 | */ 20 | public class MostUsefulProcessEngineConfiguration extends StandaloneInMemProcessEngineConfiguration { 21 | 22 | public static MostUsefulProcessEngineConfiguration mostUsefulProcessEngineConfiguration() { 23 | return new MostUsefulProcessEngineConfiguration(); 24 | } 25 | 26 | public static final Supplier SUPPLIER = new Supplier() { 27 | @Override 28 | public ProcessEngineConfiguration get() { 29 | return mostUsefulProcessEngineConfiguration(); 30 | } 31 | }; 32 | 33 | public MostUsefulProcessEngineConfiguration() { 34 | this.history = HISTORY_FULL; 35 | this.databaseSchemaUpdate = DB_SCHEMA_UPDATE_TRUE; 36 | this.jobExecutorActivate = false; 37 | this.expressionManager = new MockExpressionManager(); 38 | this.setCustomPostBPMNParseListeners(new ArrayList<>()); 39 | this.setCustomJobHandlers(new ArrayList<>()); 40 | } 41 | 42 | public void addCustomJobHandler(final JobHandler jobHandler) { 43 | getCustomJobHandlers().add(Objects.requireNonNull(jobHandler)); 44 | } 45 | 46 | public void addCustomPostBpmnParseListener(final BpmnParseListener bpmnParseListener) { 47 | getCustomPostBPMNParseListeners().add(Objects.requireNonNull(bpmnParseListener)); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/QueryMocksExample.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito; 2 | 3 | import org.camunda.bpm.engine.TaskService; 4 | import org.camunda.bpm.engine.task.Task; 5 | import org.camunda.bpm.engine.task.TaskQuery; 6 | import org.junit.Ignore; 7 | import org.junit.Test; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | import static org.mockito.Mockito.mock; 11 | import static org.mockito.Mockito.verify; 12 | 13 | @Ignore 14 | public class QueryMocksExample { 15 | 16 | private final TaskService taskService = mock(TaskService.class); 17 | private final Task task = mock(Task.class); 18 | 19 | @Test 20 | public void mock_taskQuery() { 21 | // bind query-mock to service-mock and set result to task. 22 | final TaskQuery taskQuery = null; //QueryMocks1.mockTaskQuery(taskService).singleResult(task); 23 | 24 | final Task result = taskService.createTaskQuery().active().activityInstanceIdIn("foo").excludeSubtasks().singleResult(); 25 | 26 | assertThat(result).isEqualTo(task); 27 | 28 | verify(taskQuery).active(); 29 | verify(taskQuery).activityInstanceIdIn("foo"); 30 | verify(taskQuery).excludeSubtasks(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/answer/AbstractAnswerTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.answer; 2 | 3 | import static org.mockito.Mockito.spy; 4 | import static org.mockito.Mockito.verify; 5 | import static org.mockito.Mockito.when; 6 | import static org.mockito.MockitoAnnotations.initMocks; 7 | 8 | import org.camunda.bpm.engine.delegate.VariableScope; 9 | import org.junit.Before; 10 | import org.junit.Test; 11 | import org.mockito.Mock; 12 | import org.mockito.invocation.InvocationOnMock; 13 | 14 | public class AbstractAnswerTest { 15 | 16 | private AbstractAnswer answer = spy(new AbstractAnswer() { 17 | 18 | @Override 19 | protected void answer(final VariableScope parameter) { 20 | 21 | } 22 | }); 23 | 24 | @Mock 25 | private VariableScope variableScope; 26 | 27 | @Mock 28 | private InvocationOnMock invocationOnMock; 29 | 30 | @Before 31 | public void setUp() throws Exception { 32 | initMocks(this); 33 | } 34 | 35 | @Test 36 | public void shouldDelegateToGenericAnswer() throws Throwable { 37 | when(invocationOnMock.getArguments()).thenReturn(new Object[] { variableScope }); 38 | answer.answer(invocationOnMock); 39 | verify(answer).answer(variableScope); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/answer/FluentAnswerTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.answer; 2 | 3 | import org.camunda.bpm.engine.query.Query; 4 | import org.junit.Before; 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | import org.junit.rules.ExpectedException; 8 | import org.mockito.Mock; 9 | import org.mockito.exceptions.misusing.WrongTypeOfReturnValue; 10 | import org.mockito.invocation.InvocationOnMock; 11 | 12 | import java.util.List; 13 | import java.util.Objects; 14 | 15 | import static org.assertj.core.api.Assertions.assertThat; 16 | import static org.mockito.Mockito.when; 17 | import static org.mockito.MockitoAnnotations.initMocks; 18 | 19 | public class FluentAnswerTest { 20 | 21 | @Mock 22 | private InvocationOnMock invocationOnMock; 23 | 24 | @Rule 25 | public ExpectedException expected = ExpectedException.none(); 26 | 27 | @Before 28 | public void setUp() throws Exception { 29 | initMocks(this); 30 | } 31 | 32 | @Test 33 | public void shouldReturnFluentAnserOrNull() { 34 | 35 | String string = "Bar"; 36 | FluentBuilder superType = new FluentBuilder("superType"); 37 | FluentBuilder superTypeInterface = new FluentBuilder("superInterface"); 38 | 39 | // given 40 | FluentBuilder mock = FluentAnswer.createMock(FluentBuilder.class); 41 | 42 | // the fluent mock will not be returned on super type / interface or a different type 43 | // stub three methods 44 | when(mock.string()).thenReturn(string); 45 | when(mock.superType()).thenReturn(superType); 46 | when(mock.superTypeInterface()).thenReturn(superTypeInterface); 47 | 48 | 49 | // when -> then 50 | assertThat(mock.typeMatch()).isEqualTo(mock); 51 | assertThat(mock.typeMatch("")).isEqualTo(mock); 52 | assertThat(mock.asc()).isEqualTo(mock); 53 | assertThat(mock.string()).isEqualTo(string); 54 | assertThat(mock.superType()).isEqualTo(superType); 55 | assertThat(mock.superTypeInterface()).isEqualTo(superTypeInterface); 56 | // not stubbed method -> the result is not from the answer, but is null 57 | assertThat(mock.notStubbed()).isNull(); 58 | 59 | } 60 | 61 | @Test 62 | public void shouldThrowClassCastExceptionUsingSubtypes() { 63 | 64 | expected.expect(WrongTypeOfReturnValue.class); 65 | 66 | FluentBuilder mock = FluentAnswer.createMock(FluentBuilder.class); 67 | when(mock.subType()).thenReturn(new FluentBuilderExtension()); 68 | } 69 | 70 | interface SomeAspect { 71 | } 72 | 73 | static class FluentBuilder implements SomeAspect, Query { 74 | private final String value; 75 | 76 | public FluentBuilder(String value) { 77 | this.value = value; 78 | } 79 | 80 | @Override 81 | public boolean equals(final Object o) { 82 | if (this == o) return true; 83 | if (o == null || getClass() != o.getClass()) return false; 84 | final FluentBuilder that = (FluentBuilder) o; 85 | return Objects.equals(value, that.value); 86 | } 87 | 88 | @Override 89 | public int hashCode() { 90 | return Objects.hash(value); 91 | } 92 | 93 | // object is a supertype of all objects 94 | Object superType() { 95 | return this; 96 | } 97 | 98 | // supertype 99 | SomeAspect superTypeInterface() { 100 | return this; 101 | } 102 | 103 | 104 | // full match 105 | FluentBuilder typeMatch() { 106 | return this; 107 | } 108 | 109 | // full match 110 | FluentBuilder typeMatch(String value) { 111 | return this; 112 | } 113 | 114 | // subclass of current 115 | FluentBuilderExtension subType() { 116 | return new FluentBuilderExtension(); 117 | } 118 | 119 | String notStubbed() { 120 | return "Zee"; 121 | } 122 | 123 | 124 | // not in type hierarchy 125 | String string() { 126 | return "Hello"; 127 | } 128 | 129 | @Override 130 | public FluentBuilder asc() { 131 | return null; 132 | } 133 | 134 | @Override 135 | public FluentBuilder desc() { 136 | return null; 137 | } 138 | 139 | @Override 140 | public long count() { 141 | return 0; 142 | } 143 | 144 | @Override 145 | public Object singleResult() { 146 | return null; 147 | } 148 | 149 | @Override 150 | public List list() { 151 | return null; 152 | } 153 | 154 | @Override 155 | public List unlimitedList() { 156 | return list(); 157 | } 158 | 159 | @Override 160 | public List listPage(final int firstResult, final int maxResults) { 161 | return null; 162 | } 163 | } 164 | 165 | static class FluentBuilderExtension extends FluentBuilder { 166 | FluentBuilderExtension() { 167 | super("Extension"); 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/cases/CaseExecutionFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.cases; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | public class CaseExecutionFakeTest { 8 | 9 | @Test 10 | public void testEmptyBuilder() { 11 | CaseExecutionFake fake = CaseExecutionFake.builder().build(); 12 | assertThat(fake.isActive()).isEqualTo(false); 13 | assertThat(fake.isAvailable()).isEqualTo(false); 14 | assertThat(fake.isDisabled()).isEqualTo(false); 15 | assertThat(fake.isEnabled()).isEqualTo(false); 16 | assertThat(fake.isRequired()).isEqualTo(false); 17 | assertThat(fake.isTerminated()).isEqualTo(false); 18 | } 19 | 20 | @Test 21 | public void testStateChange() { 22 | CaseExecutionFake fake = CaseExecutionFake.builder().build(); 23 | 24 | fake.setActive(true); 25 | assertThat(fake.isActive()).isEqualTo(true); 26 | 27 | fake.setAvailable(true); 28 | assertThat(fake.isAvailable()).isEqualTo(true); 29 | 30 | fake.setDisabled(true); 31 | assertThat(fake.isDisabled()).isEqualTo(true); 32 | 33 | fake.setEnabled(true); 34 | assertThat(fake.isEnabled()).isEqualTo(true); 35 | 36 | fake.setRequired(true); 37 | assertThat(fake.isRequired()).isEqualTo(true); 38 | 39 | fake.setTerminated(true); 40 | assertThat(fake.isTerminated()).isEqualTo(true); 41 | 42 | } 43 | 44 | @Test 45 | public void testFullBuilder() { 46 | CaseExecutionFake fake = CaseExecutionFake.builder() 47 | .active(true) 48 | .available(true) 49 | .disabled(true) 50 | .enabled(true) 51 | .required(true) 52 | .terminated(true) 53 | .activityDescription("activityDescription") 54 | .activityId("activityId") 55 | .activityName("activityName") 56 | .activityType("activityType") 57 | .caseDefinitionId("caseDefinitionId") 58 | .caseInstanceId("caseInstanceId") 59 | .id("id") 60 | .parentId("parentId") 61 | .tenantId("tenantId") 62 | .build(); 63 | 64 | assertThat(fake.getId()).isEqualTo("id"); 65 | assertThat(fake.getParentId()).isEqualTo("parentId"); 66 | assertThat(fake.getTenantId()).isEqualTo("tenantId"); 67 | assertThat(fake.getActivityDescription()).isEqualTo("activityDescription"); 68 | assertThat(fake.getActivityName()).isEqualTo("activityName"); 69 | assertThat(fake.getActivityType()).isEqualTo("activityType"); 70 | assertThat(fake.getActivityId()).isEqualTo("activityId"); 71 | assertThat(fake.getCaseInstanceId()).isEqualTo("caseInstanceId"); 72 | assertThat(fake.getCaseDefinitionId()).isEqualTo("caseDefinitionId"); 73 | 74 | assertThat(fake.isActive()).isEqualTo(true); 75 | assertThat(fake.isAvailable()).isEqualTo(true); 76 | assertThat(fake.isDisabled()).isEqualTo(true); 77 | assertThat(fake.isEnabled()).isEqualTo(true); 78 | assertThat(fake.isRequired()).isEqualTo(true); 79 | assertThat(fake.isTerminated()).isEqualTo(true); 80 | 81 | 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/cases/CaseInstanceFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.cases; 2 | 3 | import org.camunda.bpm.engine.CaseService; 4 | import org.camunda.bpm.engine.runtime.CaseInstance; 5 | import org.camunda.bpm.engine.variable.Variables; 6 | import org.junit.Test; 7 | 8 | import java.util.UUID; 9 | import java.util.concurrent.atomic.AtomicReference; 10 | 11 | import static org.assertj.core.api.Java6Assertions.assertThat; 12 | import static org.mockito.Mockito.mock; 13 | 14 | public class CaseInstanceFakeTest { 15 | 16 | @Test 17 | public void testEmptyBuilder() { 18 | CaseInstanceFake fake = CaseInstanceFake.builder().build(); 19 | assertThat(fake.isActive()).isEqualTo(false); 20 | assertThat(fake.isAvailable()).isEqualTo(false); 21 | assertThat(fake.isCompleted()).isEqualTo(false); 22 | assertThat(fake.isDisabled()).isEqualTo(false); 23 | assertThat(fake.isEnabled()).isEqualTo(false); 24 | assertThat(fake.isRequired()).isEqualTo(false); 25 | assertThat(fake.isTerminated()).isEqualTo(false); 26 | } 27 | 28 | @Test 29 | public void testStateChange() { 30 | CaseInstanceFake fake = CaseInstanceFake.builder().build(); 31 | 32 | fake.setActive(true); 33 | assertThat(fake.isActive()).isEqualTo(true); 34 | 35 | fake.setAvailable(true); 36 | assertThat(fake.isAvailable()).isEqualTo(true); 37 | 38 | fake.setCompleted(true); 39 | assertThat(fake.isCompleted()).isEqualTo(true); 40 | 41 | fake.setDisabled(true); 42 | assertThat(fake.isDisabled()).isEqualTo(true); 43 | 44 | fake.setEnabled(true); 45 | assertThat(fake.isEnabled()).isEqualTo(true); 46 | 47 | fake.setRequired(true); 48 | assertThat(fake.isRequired()).isEqualTo(true); 49 | 50 | fake.setTerminated(true); 51 | assertThat(fake.isTerminated()).isEqualTo(true); 52 | 53 | } 54 | 55 | @Test 56 | public void testFullBuilder() { 57 | CaseInstanceFake fake = CaseInstanceFake.builder() 58 | .businessKey("businessKey") 59 | .active(true) 60 | .available(true) 61 | .completed(true) 62 | .disabled(true) 63 | .enabled(true) 64 | .required(true) 65 | .terminated(true) 66 | .activityDescription("activityDescription") 67 | .activityId("activityId") 68 | .activityName("activityName") 69 | .activityType("activityType") 70 | .businessKey("businessKey") 71 | .caseDefinitionId("caseDefinitionId") 72 | .caseInstanceId("caseInstanceId") 73 | .id("id") 74 | .parentId("parentId") 75 | .tenantId("tenantId") 76 | .build(); 77 | 78 | assertThat(fake.getId()).isEqualTo("id"); 79 | assertThat(fake.getParentId()).isEqualTo("parentId"); 80 | assertThat(fake.getTenantId()).isEqualTo("tenantId"); 81 | assertThat(fake.getActivityDescription()).isEqualTo("activityDescription"); 82 | assertThat(fake.getActivityName()).isEqualTo("activityName"); 83 | assertThat(fake.getActivityType()).isEqualTo("activityType"); 84 | assertThat(fake.getActivityId()).isEqualTo("activityId"); 85 | assertThat(fake.getBusinessKey()).isEqualTo("businessKey"); 86 | assertThat(fake.getBusinessKey()).isEqualTo("businessKey"); 87 | assertThat(fake.getCaseInstanceId()).isEqualTo("caseInstanceId"); 88 | assertThat(fake.getCaseDefinitionId()).isEqualTo("caseDefinitionId"); 89 | 90 | assertThat(fake.isActive()).isEqualTo(true); 91 | assertThat(fake.isAvailable()).isEqualTo(true); 92 | assertThat(fake.isCompleted()).isEqualTo(true); 93 | assertThat(fake.isDisabled()).isEqualTo(true); 94 | assertThat(fake.isEnabled()).isEqualTo(true); 95 | assertThat(fake.isRequired()).isEqualTo(true); 96 | assertThat(fake.isTerminated()).isEqualTo(true); 97 | 98 | 99 | } 100 | 101 | 102 | @Test 103 | public void prepare_with_service_mock() { 104 | CaseService caseService = mock(CaseService.class); 105 | String uuid = UUID.randomUUID().toString(); 106 | String businessKey = "12"; 107 | 108 | AtomicReference reference = CaseInstanceFake.prepareMock(caseService, uuid); 109 | 110 | assertThat(reference.get()).isNull(); 111 | 112 | CaseInstance instance = caseService.createCaseInstanceByKey("case", businessKey, Variables.putValue("foo", "bar")); 113 | assertThat(reference.get()).isNotNull(); 114 | assertThat(instance.getCaseInstanceId()).isEqualTo(uuid); 115 | 116 | assertThat(caseService.getVariable(uuid, "foo")).isEqualTo("bar"); 117 | 118 | caseService.setVariable(uuid, "hello", 456); 119 | assertThat(caseService.getVariable(uuid, "hello")).isEqualTo(456); 120 | 121 | assertThat(caseService.createCaseInstanceQuery().singleResult()).isEqualTo(reference.get()); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/delegate/DelegateCaseExecutionFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.delegate; 2 | 3 | import org.camunda.bpm.engine.ProcessEngineServices; 4 | import org.camunda.bpm.engine.impl.cmmn.execution.CaseExecutionState; 5 | import org.camunda.community.mockito.CamundaMockito; 6 | import org.junit.Test; 7 | 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 10 | import static org.mockito.Mockito.mock; 11 | 12 | public class DelegateCaseExecutionFakeTest { 13 | 14 | private final DelegateCaseExecutionFake fake = CamundaMockito.delegateCaseExecutionFake(); 15 | 16 | @Test 17 | public void withId() { 18 | assertThat(fake.getId()).isNull(); 19 | fake.withId("1"); 20 | assertThat(fake.getId()).isEqualTo("1"); 21 | } 22 | 23 | @Test 24 | public void withCaseInstanceId() { 25 | assertThat(fake.getCaseInstanceId()).isNull(); 26 | fake.withCaseInstanceId("1"); 27 | assertThat(fake.getCaseInstanceId()).isEqualTo("1"); 28 | } 29 | 30 | @Test 31 | public void withEventName() { 32 | assertThat(fake.getEventName()).isNull(); 33 | fake.withEventName("create"); 34 | assertThat(fake.getEventName()).isEqualTo("create"); 35 | } 36 | 37 | @Test 38 | public void withBusinessKey() { 39 | assertThat(fake.getBusinessKey()).isNull(); 40 | fake.withBusinessKey("1"); 41 | assertThat(fake.getBusinessKey()).isEqualTo("1"); 42 | } 43 | 44 | @Test 45 | public void withCaseBusinessKey() { 46 | assertThat(fake.getCaseBusinessKey()).isNull(); 47 | fake.withCaseBusinessKey("1"); 48 | assertThat(fake.getCaseBusinessKey()).isEqualTo("1"); 49 | } 50 | 51 | @Test 52 | public void withCaseDefinitionId() { 53 | assertThat(fake.getCaseDefinitionId()).isNull(); 54 | fake.withCaseDefinitionId("1"); 55 | assertThat(fake.getCaseDefinitionId()).isEqualTo("1"); 56 | } 57 | 58 | @Test 59 | public void withParentId() { 60 | assertThat(fake.getParentId()).isNull(); 61 | fake.withParentId("1"); 62 | assertThat(fake.getParentId()).isEqualTo("1"); 63 | } 64 | 65 | @Test 66 | public void withActivityId() { 67 | assertThat(fake.getActivityId()).isNull(); 68 | fake.withActivityId("task"); 69 | assertThat(fake.getActivityId()).isEqualTo("task"); 70 | } 71 | 72 | 73 | @Test 74 | public void withActivityName() { 75 | assertThat(fake.getActivityName()).isNull(); 76 | fake.withActivityName("The Task"); 77 | assertThat(fake.getActivityName()).isEqualTo("The Task"); 78 | } 79 | 80 | @Test 81 | public void withTenantId() { 82 | assertThat(fake.getTenantId()).isNull(); 83 | fake.withTenantId("1"); 84 | assertThat(fake.getTenantId()).isEqualTo("1"); 85 | } 86 | 87 | @Test 88 | public void withProcessEngineServices() { 89 | ProcessEngineServices services = mock(ProcessEngineServices.class); 90 | assertThat(fake.getProcessEngineServices()).isNull(); 91 | fake.withProcessEngineServices(services); 92 | assertThat(fake.getProcessEngineServices()).isEqualTo(services); 93 | } 94 | 95 | @Test 96 | public void withOutState() { 97 | assertThat(fake.isActive()).isFalse(); 98 | assertThat(fake.isAvailable()).isFalse(); 99 | assertThat(fake.isClosed()).isFalse(); 100 | assertThat(fake.isCompleted()).isFalse(); 101 | assertThat(fake.isDisabled()).isFalse(); 102 | assertThat(fake.isEnabled()).isFalse(); 103 | assertThat(fake.isFailed()).isFalse(); 104 | assertThat(fake.isSuspended()).isFalse(); 105 | assertThat(fake.isTerminated()).isFalse(); 106 | } 107 | 108 | @Test 109 | public void withState_active() { 110 | fake.withCaseExecutionState(CaseExecutionState.ACTIVE); 111 | assertThat(fake.isActive()).isTrue(); 112 | } 113 | @Test 114 | public void withState_available() { 115 | fake.withCaseExecutionState(CaseExecutionState.AVAILABLE); 116 | assertThat(fake.isAvailable()).isTrue(); 117 | } 118 | @Test 119 | public void withState_closed() { 120 | fake.withCaseExecutionState(CaseExecutionState.CLOSED); 121 | assertThat(fake.isClosed()).isTrue(); 122 | } 123 | @Test 124 | public void withState_completed() { 125 | fake.withCaseExecutionState(CaseExecutionState.COMPLETED); 126 | assertThat(fake.isCompleted()).isTrue(); 127 | } 128 | @Test 129 | public void withState_disabled() { 130 | fake.withCaseExecutionState(CaseExecutionState.DISABLED); 131 | assertThat(fake.isDisabled()).isTrue(); 132 | } 133 | @Test 134 | public void withState_enabled() { 135 | fake.withCaseExecutionState(CaseExecutionState.ENABLED); 136 | assertThat(fake.isEnabled()).isTrue(); 137 | } 138 | @Test 139 | public void withState_failed() { 140 | fake.withCaseExecutionState(CaseExecutionState.FAILED); 141 | assertThat(fake.isFailed()).isTrue(); 142 | } 143 | @Test 144 | public void withState_suspended() { 145 | fake.withCaseExecutionState(CaseExecutionState.SUSPENDED); 146 | assertThat(fake.isSuspended()).isTrue(); 147 | } 148 | @Test 149 | public void withState_terminated() { 150 | fake.withCaseExecutionState(CaseExecutionState.TERMINATED); 151 | assertThat(fake.isTerminated()).isTrue(); 152 | } 153 | 154 | @Test 155 | public void modelInstance_not_supported() { 156 | assertThatThrownBy(() -> fake.getCmmnModelInstance()).isInstanceOf(UnsupportedOperationException.class); 157 | assertThatThrownBy(() -> fake.getCmmnModelElementInstance()).isInstanceOf(UnsupportedOperationException.class); 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/delegate/DelegateCaseVariableInstanceFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.delegate; 2 | 3 | import org.camunda.bpm.engine.ProcessEngineServices; 4 | import org.camunda.bpm.engine.delegate.CaseVariableListener; 5 | import org.camunda.bpm.engine.variable.impl.value.AbstractTypedValue; 6 | import org.camunda.bpm.engine.variable.type.ValueType; 7 | import org.camunda.bpm.engine.variable.value.TypedValue; 8 | import org.camunda.community.mockito.CamundaMockito; 9 | import org.junit.Test; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | import static org.mockito.Mockito.mock; 13 | 14 | public class DelegateCaseVariableInstanceFakeTest { 15 | 16 | private static TypedValue stringValue(String s) { 17 | return new AbstractTypedValue<>(s, ValueType.STRING); 18 | } 19 | 20 | private final DelegateCaseVariableInstanceFake fake = CamundaMockito.delegateCaseVariableInstanceFake(); 21 | 22 | private final DelegateCaseExecutionFake caseExecution = CamundaMockito.delegateCaseExecutionFake(); 23 | private final ProcessEngineServices processEngineServices = mock(ProcessEngineServices.class); 24 | 25 | @Test 26 | public void withFields() { 27 | 28 | fake 29 | .withActivityInstanceId("activityInstanceId") 30 | .withCaseExecutionId("caseExecutionId") 31 | .withCaseInstanceId("caseInstanceId") 32 | .withEventName("eventName") 33 | .withErrorMessage("errorMessage") 34 | .withExecutionId("executionId") 35 | .withId("id") 36 | .withName("name") 37 | .withProcessEngineServices(processEngineServices) 38 | .withProcessInstanceId("processInstanceId") 39 | .withSourceExecution(caseExecution) 40 | .withTaskId("taskId") 41 | .withTenantId("tenantId"); 42 | 43 | assertThat(fake.getActivityInstanceId()).isEqualTo("activityInstanceId"); 44 | assertThat(fake.getCaseExecutionId()).isEqualTo("caseExecutionId"); 45 | assertThat(fake.getCaseInstanceId()).isEqualTo("caseInstanceId"); 46 | assertThat(fake.getEventName()).isEqualTo("eventName"); 47 | assertThat(fake.getErrorMessage()).isEqualTo("errorMessage"); 48 | assertThat(fake.getExecutionId()).isEqualTo("executionId"); 49 | assertThat(fake.getId()).isEqualTo("id"); 50 | assertThat(fake.getName()).isEqualTo("name"); 51 | assertThat(fake.getProcessEngineServices()).isEqualTo(processEngineServices); 52 | assertThat(fake.getProcessInstanceId()).isEqualTo("processInstanceId"); 53 | assertThat(fake.getSourceExecution()).isEqualTo(caseExecution); 54 | assertThat(fake.getTaskId()).isEqualTo("taskId"); 55 | assertThat(fake.getTenantId()).isEqualTo("tenantId"); 56 | assertThat(fake.getTypeName()).isEqualTo("undefined"); 57 | } 58 | 59 | @Test 60 | public void withTypedValue() { 61 | fake.withValue(new AbstractTypedValue<>("foo", ValueType.STRING)); 62 | 63 | assertThat(fake.getTypedValue().getType()).isEqualTo(ValueType.STRING); 64 | assertThat(fake.getTypedValue().getValue()).isEqualTo("foo"); 65 | } 66 | 67 | @Test 68 | public void withValue_undefined() { 69 | fake.withValue(1L); 70 | 71 | assertThat(fake.getTypedValue().getValue()).isEqualTo(1L); 72 | assertThat(fake.getTypedValue().getType()).isNull(); 73 | } 74 | 75 | @Test 76 | public void variable_create() { 77 | fake.create("foo", stringValue("bar")); 78 | 79 | assertThat(fake.getName()).isEqualTo("foo"); 80 | assertThat(fake.getTypedValue().getValue()).isEqualTo("bar"); 81 | assertThat(fake.getTypeName()).isEqualTo("string"); 82 | assertThat(fake.getTypedValue().getType()).isEqualTo(ValueType.STRING); 83 | assertThat(fake.getEventName()).isEqualTo(CaseVariableListener.CREATE); 84 | } 85 | 86 | @Test 87 | public void variable_update() { 88 | fake.update("foo", stringValue("bar")); 89 | 90 | assertThat(fake.getName()).isEqualTo("foo"); 91 | assertThat(fake.getTypedValue().getValue()).isEqualTo("bar"); 92 | assertThat(fake.getTypeName()).isEqualTo("string"); 93 | assertThat(fake.getTypedValue().getType()).isEqualTo(ValueType.STRING); 94 | assertThat(fake.getEventName()).isEqualTo(CaseVariableListener.UPDATE); 95 | } 96 | 97 | @Test 98 | public void variable_delete() { 99 | fake.delete("foo", stringValue("bar")); 100 | 101 | assertThat(fake.getName()).isEqualTo("foo"); 102 | assertThat(fake.getTypedValue().getValue()).isEqualTo("bar"); 103 | assertThat(fake.getTypeName()).isEqualTo("string"); 104 | assertThat(fake.getTypedValue().getType()).isEqualTo(ValueType.STRING); 105 | assertThat(fake.getEventName()).isEqualTo(CaseVariableListener.DELETE); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/delegate/DelegateExecutionFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.delegate; 2 | 3 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 4 | import org.camunda.bpm.engine.runtime.Incident; 5 | import org.camunda.bpm.engine.variable.Variables; 6 | import org.camunda.community.mockito.CamundaMockito; 7 | import org.junit.Test; 8 | 9 | import static io.holunda.camunda.bpm.data.CamundaBpmData.stringVariable; 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | 12 | public class DelegateExecutionFakeTest { 13 | 14 | private final DelegateExecutionFake delegate = CamundaMockito.delegateExecutionFake(); 15 | 16 | @Test 17 | public void with_variable_local() { 18 | delegate.withVariableLocal("foo", 1) 19 | .withVariablesLocal(Variables.putValue("bar", 2)) 20 | .withBusinessKey("123"); 21 | 22 | assertThat(delegate.getVariableLocal("foo")).isEqualTo(1); 23 | assertThat(delegate.getVariableLocal("bar")).isEqualTo(2); 24 | } 25 | 26 | @Test 27 | public void with_variable_local_via_factory() { 28 | VariableFactory fooVariable = stringVariable("foo"); 29 | 30 | delegate.withVariableLocal(fooVariable, "1"); 31 | 32 | assertThat(fooVariable.from(delegate).getLocal()).isEqualTo("1"); 33 | } 34 | 35 | @Test 36 | public void create_and_resolve_incident() { 37 | assertThat(delegate.getIncidents()).isEmpty(); 38 | Incident incident = delegate.createIncident("type", "config", "message"); 39 | 40 | assertThat(delegate.getIncidents().get(incident.getId())).isNotNull(); 41 | 42 | delegate.resolveIncident(incident.getId()); 43 | assertThat(delegate.getIncidents()).isEmpty(); 44 | } 45 | 46 | @Test 47 | public void model_element_type() { 48 | delegate.withBpmnModelElementInstanceType("userTask"); 49 | assertThat(delegate.getBpmnModelElementInstance().getElementType().getTypeName()).isEqualTo("userTask"); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/delegate/ProcessEngineServicesAwareFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.delegate; 2 | 3 | import org.camunda.bpm.engine.ProcessEngine; 4 | import org.camunda.bpm.engine.ProcessEngineServices; 5 | import org.junit.Test; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | import static org.mockito.Mockito.mock; 9 | 10 | public class ProcessEngineServicesAwareFakeTest { 11 | 12 | 13 | private final ProcessEngineServicesAwareFake fake = new ProcessEngineServicesAwareFake(); 14 | 15 | 16 | @Test 17 | public void initially_not_set() { 18 | assertThat(fake.getProcessEngine()).isNull(); 19 | assertThat(fake.getProcessEngineServices()).isNull(); 20 | } 21 | 22 | @Test 23 | public void with_processEngineServices() { 24 | ProcessEngineServices processEngineServices = mock(ProcessEngineServices.class); 25 | 26 | fake.withProcessEngineServices(processEngineServices); 27 | 28 | assertThat(fake.getProcessEngine()).isNull(); 29 | assertThat(fake.getProcessEngineServices()).isNotNull(); 30 | } 31 | 32 | @Test 33 | public void with_processEngine_sets_both() { 34 | ProcessEngine processEngine = mock(ProcessEngine.class); 35 | 36 | fake.withProcessEngine(processEngine); 37 | 38 | assertThat(fake.getProcessEngine()).isNotNull().isEqualTo(processEngine); 39 | assertThat(fake.getProcessEngineServices()).isNotNull().isEqualTo(processEngine); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/delegate/VariableScopeFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.delegate; 2 | 3 | 4 | import io.holunda.camunda.bpm.data.CamundaBpmData; 5 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 6 | import org.camunda.bpm.engine.variable.VariableMap; 7 | import org.camunda.bpm.engine.variable.Variables; 8 | import org.camunda.bpm.engine.variable.value.StringValue; 9 | import org.camunda.community.mockito.CamundaMockito; 10 | import org.junit.Test; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | import static org.camunda.bpm.engine.variable.Variables.stringValue; 14 | 15 | public class VariableScopeFakeTest { 16 | 17 | private final VariableScopeFake variableScope = CamundaMockito.variableScopeFake(); 18 | 19 | @Test 20 | public void create_withVariable() throws Exception { 21 | variableScope.withVariable("foo", 1).withVariables(Variables.putValue("bar", 2)); 22 | 23 | assertThat(variableScope.getVariableNames()).containsOnly("foo", "bar"); 24 | } 25 | 26 | @Test 27 | public void variablesTyped() throws Exception { 28 | VariableMap variables = Variables.putValueTyped("foo", stringValue("bar")); 29 | 30 | variableScope.setVariablesLocal(variables); 31 | 32 | StringValue foo = variableScope.getVariableLocalTyped("foo"); 33 | 34 | assertThat(foo.getValue()).isEqualTo("bar"); 35 | } 36 | 37 | @Test 38 | public void variable_from_factory() { 39 | VariableFactory foo = CamundaBpmData.stringVariable("foo"); 40 | VariableFactory bar = CamundaBpmData.intVariable("bar"); 41 | 42 | variableScope 43 | .withVariable(foo, "1") 44 | .withVariable(bar, 1); 45 | 46 | assertThat(foo.from(variableScope).get()).isEqualTo("1"); 47 | assertThat(bar.from(variableScope).get()).isEqualTo(1); 48 | } 49 | 50 | @Test 51 | public void variablesLocal() throws Exception { 52 | VariableMap variables = Variables.putValue("foo", "bar"); 53 | variableScope.setVariablesLocal(variables); 54 | 55 | String foo = (String) variableScope.getVariableLocal("foo"); 56 | 57 | assertThat(foo).isEqualTo("bar"); 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/function/NameForExpressionTypeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.function; 2 | 3 | 4 | import static org.assertj.core.api.Assertions.assertThat; 5 | import static org.camunda.community.mockito.function.NameForType.juelNameFor; 6 | import static org.mockito.Mockito.mock; 7 | 8 | import javax.inject.Named; 9 | 10 | import org.junit.Test; 11 | import org.springframework.stereotype.Component; 12 | import org.springframework.stereotype.Service; 13 | 14 | public class NameForExpressionTypeTest { 15 | 16 | public static class PojoBean { 17 | } 18 | 19 | @Named 20 | public static class NamedBean { 21 | } 22 | 23 | @Named("bar") 24 | public static class BarNamedBean { 25 | } 26 | 27 | @Component 28 | public static class ComponentBean { 29 | } 30 | 31 | @Component("bar") 32 | public static class BarComponentBean { 33 | } 34 | 35 | @Service 36 | public static class ServiceBean { 37 | } 38 | 39 | @Service("bar") 40 | public static class BarServiceBean { 41 | } 42 | 43 | 44 | @Test 45 | public void resolves_pojo() { 46 | assertThat(juelNameFor(PojoBean.class)).isEqualTo("pojoBean"); 47 | } 48 | 49 | @Test 50 | public void resolves_named_default() { 51 | assertThat(juelNameFor(NamedBean.class)).isEqualTo("namedBean"); 52 | } 53 | 54 | @Test 55 | public void resolves_named_bar() { 56 | assertThat(juelNameFor(BarNamedBean.class)).isEqualTo("bar"); 57 | } 58 | 59 | @Test 60 | public void resolves_component() { 61 | assertThat(juelNameFor(ComponentBean.class)).isEqualTo("componentBean"); 62 | } 63 | 64 | @Test 65 | public void resolves_named_component() { 66 | assertThat(juelNameFor(BarComponentBean.class)).isEqualTo("bar"); 67 | } 68 | 69 | @Test 70 | public void resolves_service() { 71 | assertThat(juelNameFor(ServiceBean.class)).isEqualTo("serviceBean"); 72 | } 73 | 74 | @Test 75 | public void resolves_named_service() { 76 | assertThat(juelNameFor(BarServiceBean.class)).isEqualTo("bar"); 77 | } 78 | 79 | @Test 80 | public void gets_value_from_component() { 81 | assertThat(NameForType.GET_VALUE.apply(BarComponentBean.class.getAnnotation(Component.class))).isEqualTo("bar"); 82 | assertThat(NameForType.GET_VALUE.apply(ComponentBean.class.getAnnotation(Component.class))).isEqualTo(""); 83 | } 84 | 85 | @Test 86 | public void gets_value_from_service() { 87 | assertThat(NameForType.GET_VALUE.apply(BarServiceBean.class.getAnnotation(Service.class))).isEqualTo("bar"); 88 | assertThat(NameForType.GET_VALUE.apply(ServiceBean.class.getAnnotation(Service.class))).isEqualTo(""); 89 | } 90 | 91 | @Test 92 | public void gets_name_for_mock_byClass() throws Exception { 93 | assertThat(NameForType.juelNameFor(mock(NamedBean.class))).isEqualTo("namedBean"); 94 | } 95 | 96 | @Test 97 | public void gets_name_for_mock_byAnnotation() throws Exception { 98 | assertThat(NameForType.juelNameFor(mock(BarNamedBean.class))).isEqualTo("bar"); 99 | } 100 | 101 | @Test 102 | public void getTypeOfMock() throws Exception { 103 | assertThat(NameForType.typeOf(mock(BarNamedBean.class)).getSimpleName()).isEqualTo(BarNamedBean.class.getSimpleName()); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/function/ParseDelegateExpressionsTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.function; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import java.net.URL; 6 | import java.util.List; 7 | 8 | import org.apache.commons.lang3.tuple.Pair; 9 | import org.junit.Test; 10 | 11 | public class ParseDelegateExpressionsTest { 12 | 13 | 14 | private final ParseDelegateExpressions function = new ParseDelegateExpressions(); 15 | 16 | @Test 17 | public void gets_pairs_for_mockProcess() { 18 | final URL bpmnFile = this.getClass().getResource("/MockProcess.bpmn"); 19 | final List> pairs = function.apply(bpmnFile); 20 | 21 | assertThat(pairs).isNotEmpty(); 22 | } 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/function/ReadXmlDocumentFromResourceTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.function; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import javax.xml.transform.TransformerException; 6 | 7 | import java.net.URL; 8 | 9 | import org.junit.Test; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import org.w3c.dom.Document; 13 | import org.w3c.dom.Element; 14 | import org.w3c.dom.NodeList; 15 | 16 | 17 | public class ReadXmlDocumentFromResourceTest { 18 | 19 | private final Logger logger = LoggerFactory.getLogger(getClass()); 20 | private final ReadXmlDocumentFromResource fromResource = new ReadXmlDocumentFromResource(); 21 | 22 | @Test 23 | public void returns_document_for_resource() throws TransformerException { 24 | Document document = fromResource.apply(getResource("/MockProcess.bpmn")); 25 | assertThat(document).isNotNull(); 26 | String content = ReadXmlDocumentFromResource.TO_STRING.apply(document); 27 | assertThat(content).contains("#{loadData}"); 28 | } 29 | 30 | @Test 31 | public void parse_xml() { 32 | Document document = fromResource.apply(getResource("/MockProcess.bpmn")); 33 | 34 | Element root = document.getDocumentElement(); 35 | final NodeList tasks = root.getElementsByTagNameNS("*", "serviceTask"); 36 | 37 | assertThat(tasks.getLength()).isEqualTo(2); 38 | 39 | logger.info(tasks.toString()); 40 | logger.info(tasks.item(1).toString()); 41 | 42 | } 43 | 44 | private URL getResource(String name) { 45 | return this.getClass().getResource(name); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/mock/FluentExecutionListenerMockTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.mock; 2 | 3 | import org.camunda.bpm.engine.delegate.BpmnError; 4 | import org.camunda.community.mockito.DelegateExpressions; 5 | import org.camunda.community.mockito.delegate.DelegateExecutionFake; 6 | import org.junit.Test; 7 | 8 | import java.util.Map; 9 | 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 12 | 13 | public class FluentExecutionListenerMockTest { 14 | 15 | private static final String BEAN_NAME = "foo"; 16 | private static final String MESSAGE = "message"; 17 | private final FluentExecutionListenerMock executionListener = DelegateExpressions.registerExecutionListenerMock(BEAN_NAME); 18 | 19 | private final DelegateExecutionFake delegateExecution = new DelegateExecutionFake(); 20 | 21 | @Test 22 | public void throws_bpmnError() { 23 | executionListener.onExecutionThrowBpmnError("code", MESSAGE); 24 | assertThatThrownBy(() -> executionListener.notify(delegateExecution)) 25 | .isInstanceOf(BpmnError.class) 26 | .hasMessage(MESSAGE); 27 | } 28 | 29 | @Test 30 | public void set_single_variable() throws Exception { 31 | executionListener.onExecutionSetVariable("foo", "bar"); 32 | 33 | executionListener.notify(delegateExecution); 34 | 35 | assertThat(delegateExecution.hasVariable("foo")).isTrue(); 36 | assertThat((String) delegateExecution.getVariable("foo")).isEqualTo("bar"); 37 | } 38 | 39 | @Test 40 | public void consecutive_set_variables() throws Exception { 41 | executionListener.onExecutionSetVariables(Map.of("foo", "bar"), Map.of("bar", "foo")); 42 | 43 | executionListener.notify(delegateExecution); 44 | 45 | assertThat(delegateExecution.hasVariable("foo")).isTrue(); 46 | assertThat((String) delegateExecution.getVariable("foo")).isEqualTo("bar"); 47 | 48 | executionListener.notify(delegateExecution); 49 | 50 | assertThat(delegateExecution.hasVariable("bar")).isTrue(); 51 | assertThat((String) delegateExecution.getVariable("bar")).isEqualTo("foo"); 52 | } 53 | 54 | @Test 55 | public void consecutive_set_variables_three_times() throws Exception { 56 | executionListener.onExecutionSetVariables(Map.of("foo", "bar"), Map.of("bar", "foo")); 57 | 58 | executionListener.notify(delegateExecution); 59 | 60 | assertThat(delegateExecution.hasVariable("foo")).isTrue(); 61 | assertThat((String) delegateExecution.getVariable("foo")).isEqualTo("bar"); 62 | 63 | executionListener.notify(delegateExecution); 64 | 65 | assertThat(delegateExecution.hasVariable("bar")).isTrue(); 66 | assertThat((String) delegateExecution.getVariable("bar")).isEqualTo("foo"); 67 | 68 | executionListener.notify(delegateExecution); 69 | 70 | assertThat(delegateExecution.hasVariable("bar")).isTrue(); 71 | assertThat((String) delegateExecution.getVariable("bar")).isEqualTo("foo"); 72 | } 73 | 74 | @Test 75 | public void consecutive_set_variables_map() throws Exception { 76 | executionListener.onExecutionSetVariables(Map.of("foo", "bar")); 77 | 78 | executionListener.notify(delegateExecution); 79 | 80 | assertThat(delegateExecution.hasVariable("foo")).isTrue(); 81 | assertThat((String) delegateExecution.getVariable("foo")).isEqualTo("bar"); 82 | 83 | executionListener.notify(delegateExecution); 84 | 85 | assertThat(delegateExecution.hasVariable("foo")).isTrue(); 86 | assertThat((String) delegateExecution.getVariable("foo")).isEqualTo("bar"); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/mock/FluentJavaDelegateMockTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.mock; 2 | 3 | import io.holunda.camunda.bpm.data.CamundaBpmData; 4 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 5 | import org.camunda.bpm.engine.delegate.BpmnError; 6 | import org.camunda.community.mockito.DelegateExpressions; 7 | import org.camunda.community.mockito.delegate.DelegateExecutionFake; 8 | import org.junit.Test; 9 | 10 | import java.util.Map; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 14 | 15 | public class FluentJavaDelegateMockTest { 16 | 17 | private static final String BEAN_NAME = "foo"; 18 | private static final String MESSAGE = "message"; 19 | 20 | private final FluentJavaDelegateMock delegate = DelegateExpressions.registerJavaDelegateMock(BEAN_NAME); 21 | private final DelegateExecutionFake execution = DelegateExecutionFake.of(); 22 | 23 | @Test 24 | public void throws_bpmnError() { 25 | delegate.onExecutionThrowBpmnError("code", MESSAGE); 26 | 27 | // test succeeds when exception is thrown 28 | assertThatThrownBy(() -> delegate.execute(execution)) 29 | .isInstanceOf(BpmnError.class) 30 | .hasMessage(MESSAGE); 31 | 32 | } 33 | 34 | @Test 35 | public void throws_exception() { 36 | delegate.onExecutionThrowException(new NullPointerException()); 37 | 38 | assertThatThrownBy(() -> delegate.execute(execution)) 39 | .isInstanceOf(NullPointerException.class); 40 | } 41 | 42 | @Test 43 | public void set_single_variable() throws Exception { 44 | delegate.onExecutionSetVariable("foo", "bar"); 45 | 46 | delegate.execute(execution); 47 | 48 | assertThat(execution.hasVariable("foo")).isTrue(); 49 | assertThat((String) execution.getVariable("foo")).isEqualTo("bar"); 50 | } 51 | 52 | @Test 53 | public void set_single_variable_via_factory() throws Exception { 54 | VariableFactory foo = CamundaBpmData.stringVariable("foo"); 55 | 56 | delegate.onExecutionSetVariable(foo, "bar"); 57 | 58 | delegate.execute(execution); 59 | 60 | assertThat(execution.hasVariable("foo")).isTrue(); 61 | assertThat(foo.from(execution).get()).isEqualTo("bar"); 62 | } 63 | 64 | @Test 65 | public void consecutive_set_variables() throws Exception { 66 | delegate.onExecutionSetVariables(Map.of("foo", "bar"), Map.of("bar", "foo")); 67 | 68 | delegate.execute(execution); 69 | 70 | assertThat(execution.hasVariable("foo")).isTrue(); 71 | assertThat((String) execution.getVariable("foo")).isEqualTo("bar"); 72 | 73 | delegate.execute(execution); 74 | 75 | assertThat(execution.hasVariable("bar")).isTrue(); 76 | assertThat((String) execution.getVariable("bar")).isEqualTo("foo"); 77 | } 78 | 79 | @Test 80 | public void consecutive_set_variables_three_times() throws Exception { 81 | delegate.onExecutionSetVariables(Map.of("foo", "bar"), Map.of("bar", "foo")); 82 | 83 | delegate.execute(execution); 84 | 85 | assertThat(execution.hasVariable("foo")).isTrue(); 86 | assertThat((String) execution.getVariable("foo")).isEqualTo("bar"); 87 | 88 | delegate.execute(execution); 89 | 90 | assertThat(execution.hasVariable("bar")).isTrue(); 91 | assertThat((String) execution.getVariable("bar")).isEqualTo("foo"); 92 | 93 | delegate.execute(execution); 94 | 95 | assertThat(execution.hasVariable("bar")).isTrue(); 96 | assertThat((String) execution.getVariable("bar")).isEqualTo("foo"); 97 | } 98 | 99 | @Test 100 | public void consecutive_set_variables_map() throws Exception { 101 | delegate.onExecutionSetVariables(Map.of("foo", "bar")); 102 | 103 | delegate.execute(execution); 104 | 105 | assertThat(execution.hasVariable("foo")).isTrue(); 106 | assertThat((String) execution.getVariable("foo")).isEqualTo("bar"); 107 | 108 | delegate.execute(execution); 109 | 110 | assertThat(execution.hasVariable("foo")).isTrue(); 111 | assertThat((String) execution.getVariable("foo")).isEqualTo("bar"); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/mock/FluentMockTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.mock; 2 | 3 | import org.camunda.bpm.engine.variable.VariableMap; 4 | import org.camunda.bpm.engine.variable.impl.VariableMapImpl; 5 | import org.junit.Test; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | 9 | public class FluentMockTest { 10 | 11 | @Test 12 | public void put_in_front_of_nothing() { 13 | VariableMap variableMap = new VariableMapImpl(); 14 | VariableMap[] variableMaps = FluentMock.combineVariableMaps(variableMap); 15 | assertThat(variableMaps) 16 | .hasSize(1) 17 | .contains(variableMap); 18 | } 19 | 20 | @Test 21 | public void put_in_front_of_one_element() { 22 | VariableMap variableMap1 = new VariableMapImpl(); 23 | VariableMap variableMap2 = new VariableMapImpl(); 24 | VariableMap[] variableMaps = FluentMock.combineVariableMaps(variableMap1, variableMap2); 25 | assertThat(variableMaps) 26 | .hasSize(2) 27 | .contains(variableMap1, variableMap2); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/mock/FluentTaskListenerMockTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.mock; 2 | 3 | import org.camunda.bpm.engine.delegate.BpmnError; 4 | import org.camunda.community.mockito.DelegateExpressions; 5 | import org.camunda.community.mockito.delegate.DelegateTaskFake; 6 | import org.junit.Test; 7 | 8 | import java.util.Map; 9 | 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 12 | 13 | public class FluentTaskListenerMockTest { 14 | 15 | private static final String BEAN_NAME = "foo"; 16 | private static final String MESSAGE = "message"; 17 | private final FluentTaskListenerMock taskListener = DelegateExpressions.registerTaskListenerMock(BEAN_NAME); 18 | 19 | private final DelegateTaskFake delegateTask = new DelegateTaskFake(); 20 | 21 | @Test 22 | public void throws_bpmnError() { 23 | taskListener.onExecutionThrowBpmnError("code", MESSAGE); 24 | assertThatThrownBy(() -> taskListener.notify(delegateTask)) 25 | .isInstanceOf(BpmnError.class) 26 | .hasMessage(MESSAGE); 27 | } 28 | 29 | @Test 30 | public void set_single_variable() { 31 | taskListener.onExecutionSetVariable("foo", "bar"); 32 | 33 | taskListener.notify(delegateTask); 34 | 35 | assertThat(delegateTask.hasVariable("foo")).isTrue(); 36 | assertThat((String) delegateTask.getVariable("foo")).isEqualTo("bar"); 37 | } 38 | 39 | @Test 40 | public void consecutive_set_variables() { 41 | taskListener.onExecutionSetVariables(Map.of("foo", "bar"), Map.of("bar", "foo")); 42 | 43 | taskListener.notify(delegateTask); 44 | 45 | assertThat(delegateTask.hasVariable("foo")).isTrue(); 46 | assertThat((String) delegateTask.getVariable("foo")).isEqualTo("bar"); 47 | 48 | taskListener.notify(delegateTask); 49 | 50 | assertThat(delegateTask.hasVariable("bar")).isTrue(); 51 | assertThat((String) delegateTask.getVariable("bar")).isEqualTo("foo"); 52 | } 53 | 54 | @Test 55 | public void consecutive_set_variables_three_times() { 56 | taskListener.onExecutionSetVariables(Map.of("foo", "bar"), Map.of("bar", "foo")); 57 | 58 | taskListener.notify(delegateTask); 59 | 60 | assertThat(delegateTask.hasVariable("foo")).isTrue(); 61 | assertThat((String) delegateTask.getVariable("foo")).isEqualTo("bar"); 62 | 63 | taskListener.notify(delegateTask); 64 | 65 | assertThat(delegateTask.hasVariable("bar")).isTrue(); 66 | assertThat((String) delegateTask.getVariable("bar")).isEqualTo("foo"); 67 | 68 | taskListener.notify(delegateTask); 69 | 70 | assertThat(delegateTask.hasVariable("bar")).isTrue(); 71 | assertThat((String) delegateTask.getVariable("bar")).isEqualTo("foo"); 72 | } 73 | 74 | @Test 75 | public void consecutive_set_variables_map() { 76 | taskListener.onExecutionSetVariables(Map.of("foo", "bar")); 77 | 78 | taskListener.notify(delegateTask); 79 | 80 | assertThat(delegateTask.hasVariable("foo")).isTrue(); 81 | assertThat((String) delegateTask.getVariable("foo")).isEqualTo("bar"); 82 | 83 | taskListener.notify(delegateTask); 84 | 85 | assertThat(delegateTask.hasVariable("foo")).isTrue(); 86 | assertThat((String) delegateTask.getVariable("foo")).isEqualTo("bar"); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/process/ProcessDefinitionFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.process; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | public class ProcessDefinitionFakeTest { 8 | 9 | @Test 10 | public void testEmptyBuilder() { 11 | ProcessDefinitionFake fake = ProcessDefinitionFake.builder().build(); 12 | assertThat(fake.isSuspended()).isFalse(); 13 | assertThat(fake.hasStartFormKey()).isFalse(); 14 | assertThat(fake.getHistoryTimeToLive()).isEqualTo(0); 15 | assertThat(fake.getVersion()).isEqualTo(0); 16 | } 17 | 18 | @Test 19 | public void testStateChange() { 20 | ProcessDefinitionFake fake = ProcessDefinitionFake.builder().build(); 21 | assertThat(fake.isSuspended()).isFalse(); 22 | fake.setSuspended(true); 23 | assertThat(fake.isSuspended()).isTrue(); 24 | } 25 | 26 | 27 | @Test 28 | public void testBuilder() { 29 | ProcessDefinitionFake fake = ProcessDefinitionFake 30 | .builder() 31 | .category("cat") 32 | .deploymentId("deploymentId") 33 | .description("description") 34 | .diagramResourceName("diagramResourceName") 35 | .hasStartForm(true) 36 | .historyTimeToLive(17) 37 | .id("id") 38 | .key("key") 39 | .name("name") 40 | .resourceName("resourceName") 41 | .suspended(true) 42 | .tenantId("tenantId") 43 | .versionTag("versionTag") 44 | .version(16) 45 | .build(); 46 | 47 | assertThat(fake.getCategory()).isEqualTo("cat"); 48 | assertThat(fake.getDeploymentId()).isEqualTo("deploymentId"); 49 | assertThat(fake.getDescription()).isEqualTo("description"); 50 | assertThat(fake.getDiagramResourceName()).isEqualTo("diagramResourceName"); 51 | assertThat(fake.getHistoryTimeToLive()).isEqualTo(17); 52 | assertThat(fake.hasStartFormKey()).isTrue(); 53 | assertThat(fake.getId()).isEqualTo("id"); 54 | assertThat(fake.getName()).isEqualTo("name"); 55 | assertThat(fake.getResourceName()).isEqualTo("resourceName"); 56 | assertThat(fake.isSuspended()).isTrue(); 57 | assertThat(fake.getTenantId()).isEqualTo("tenantId"); 58 | assertThat(fake.getVersionTag()).isEqualTo("versionTag"); 59 | assertThat(fake.getVersion()).isEqualTo(16); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/process/ProcessInstanceFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.process; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.assertj.core.api.Java6Assertions.assertThat; 6 | 7 | public class ProcessInstanceFakeTest { 8 | 9 | @Test 10 | public void testEmptyBuilder() { 11 | ProcessInstanceFake fake = ProcessInstanceFake.builder().build(); 12 | assertThat(fake.isEnded()).isEqualTo(false); 13 | assertThat(fake.isSuspended()).isEqualTo(false); 14 | } 15 | 16 | @Test 17 | public void testStateChange() { 18 | ProcessInstanceFake fake = ProcessInstanceFake.builder().build(); 19 | assertThat(fake.isEnded()).isEqualTo(false); 20 | assertThat(fake.isSuspended()).isEqualTo(false); 21 | 22 | fake.setEnded(true); 23 | assertThat(fake.isEnded()).isEqualTo(true); 24 | 25 | fake.setSuspended(true); 26 | assertThat(fake.isSuspended()).isEqualTo(true); 27 | } 28 | 29 | @Test 30 | public void testFullBuilder() { 31 | ProcessInstanceFake fake = ProcessInstanceFake.builder() 32 | .businessKey("businessKey") 33 | .caseInstanceId("caseInstanceId") 34 | .ended(true) 35 | .id("id") 36 | .processDefinitionId("processDefinitionId") 37 | .processInstanceId("processInstanceId") 38 | .suspended(true) 39 | .tenantId("tenantId") 40 | .build(); 41 | 42 | assertThat(fake.getBusinessKey()).isEqualTo("businessKey"); 43 | assertThat(fake.getCaseInstanceId()).isEqualTo("caseInstanceId"); 44 | assertThat(fake.getId()).isEqualTo("id"); 45 | assertThat(fake.getProcessDefinitionId()).isEqualTo("processDefinitionId"); 46 | assertThat(fake.getProcessInstanceId()).isEqualTo("processInstanceId"); 47 | assertThat(fake.isSuspended()).isEqualTo(true); 48 | assertThat(fake.isEnded()).isEqualTo(true); 49 | 50 | 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/query/AuthorizationQueryMockTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.mockito.Mockito.mock; 5 | import static org.mockito.Mockito.verify; 6 | 7 | import org.camunda.bpm.engine.AuthorizationService; 8 | import org.camunda.bpm.engine.authorization.Authorization; 9 | import org.camunda.bpm.engine.authorization.AuthorizationQuery; 10 | //import org.camunda.community.mockito.QueryMocks1; 11 | import org.camunda.community.mockito.QueryMocks; 12 | import org.junit.Ignore; 13 | import org.junit.Test; 14 | 15 | public class AuthorizationQueryMockTest { 16 | 17 | private final AuthorizationService serviceMock = mock(AuthorizationService.class); 18 | private final Authorization authorization = mock(Authorization.class); 19 | 20 | @Test 21 | public void mock_authorizationQuery() { 22 | final AuthorizationQuery query = QueryMocks.mockAuthorizationQuery(serviceMock) 23 | .singleResult(authorization); 24 | 25 | // @formatter:off 26 | final Authorization result = serviceMock.createAuthorizationQuery() 27 | .authorizationId("foo") 28 | .authorizationType(1) 29 | .userIdIn("user") 30 | .singleResult(); 31 | // @formatter:on 32 | 33 | assertThat(result).isEqualTo(authorization); 34 | 35 | verify(query).userIdIn("user"); 36 | verify(query).authorizationId("foo"); 37 | verify(query).authorizationType(1); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/query/ProcessInstanceQueryMockTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.assertj.core.util.Lists; 4 | import org.camunda.bpm.engine.RuntimeService; 5 | import org.camunda.bpm.engine.runtime.ProcessInstance; 6 | import org.camunda.community.mockito.CamundaMockito; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.mockito.Mock; 10 | import org.mockito.junit.MockitoJUnitRunner; 11 | 12 | import java.util.List; 13 | 14 | import static org.assertj.core.api.Assertions.assertThat; 15 | import static org.mockito.Mockito.mock; 16 | 17 | @RunWith(MockitoJUnitRunner.class) 18 | public class ProcessInstanceQueryMockTest { 19 | 20 | @Mock 21 | private RuntimeService runtimeServiceMock; 22 | 23 | @Test 24 | public void should_not_throw_stubbing_exception_on_only_single_result() { 25 | 26 | // GIVEN 27 | CamundaMockito.mockProcessInstanceQuery(runtimeServiceMock) 28 | .singleResult(mock(ProcessInstance.class)); 29 | 30 | // WHEN 31 | final ProcessInstance result = runtimeServiceMock.createProcessInstanceQuery() 32 | .processInstanceId("test") 33 | .singleResult(); 34 | // THEN 35 | assertThat(result).isNotNull(); 36 | } 37 | 38 | @Test 39 | public void should_not_throw_stubbing_exception_on_only_list() { 40 | 41 | // GIVEN 42 | CamundaMockito.mockProcessInstanceQuery(runtimeServiceMock) 43 | .list(Lists.newArrayList(mock(ProcessInstance.class))); 44 | 45 | // WHEN 46 | final List result = runtimeServiceMock.createProcessInstanceQuery() 47 | .processInstanceId("test") 48 | .list(); 49 | // THEN 50 | assertThat(result).isNotNull(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/query/TaskQueryMockTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.query; 2 | 3 | import org.camunda.bpm.engine.TaskService; 4 | import org.camunda.bpm.engine.task.Task; 5 | import org.camunda.bpm.engine.task.TaskQuery; 6 | import org.camunda.community.mockito.CamundaMockito; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.mockito.Mock; 10 | import org.mockito.Mockito; 11 | import org.mockito.junit.MockitoJUnitRunner; 12 | 13 | import java.util.Date; 14 | 15 | import static org.assertj.core.api.Assertions.assertThat; 16 | import static org.mockito.Mockito.verify; 17 | 18 | //import org.camunda.community.mockito.QueryMocks1; 19 | 20 | @RunWith(MockitoJUnitRunner.class) 21 | public class TaskQueryMockTest { 22 | 23 | @Mock 24 | private TaskService taskService; 25 | 26 | @Mock 27 | private Task singleResult; 28 | 29 | @Test 30 | public void should_mock_query_and_return_singleResult() { 31 | final TaskQuery taskQuery = CamundaMockito.mockTaskQuery(taskService).singleResult(singleResult); 32 | assertThat(taskService.createTaskQuery().singleResult()).isEqualTo(singleResult); 33 | 34 | Mockito.verify(taskQuery).singleResult(); 35 | } 36 | 37 | @Test 38 | public void singleResult_for_activityName() { 39 | CamundaMockito.mockTaskQuery(taskService).singleResult(singleResult); 40 | assertThat(taskService.createTaskQuery().taskDefinitionKey("").singleResult()).isEqualTo(singleResult); 41 | } 42 | 43 | @Test 44 | public void singleResult_for_everything() { 45 | final TaskQuery taskQuery = new TaskQueryMock().forService(taskService).singleResult(singleResult); 46 | // @formatter:off 47 | assertThat( 48 | taskService.createTaskQuery() 49 | .taskDefinitionKey("") 50 | .processInstanceBusinessKey("") 51 | .taskDefinitionKey("") 52 | .taskId("") 53 | .taskUnassigned() 54 | .processInstanceId("pid") 55 | .active() 56 | .activityInstanceIdIn("") 57 | .dueAfter(new Date()) 58 | .dueBefore(new Date()) 59 | .dueDate(new Date()) 60 | .excludeSubtasks() 61 | .executionId("") 62 | .processDefinitionId("") 63 | .processDefinitionKey("") 64 | .asc() 65 | .desc() 66 | .singleResult()).isEqualTo(singleResult); 67 | // @formatter:on 68 | 69 | verify(taskQuery).processInstanceId("pid"); 70 | } 71 | 72 | @Test 73 | public void count_on_taskQuery() throws Exception { 74 | final TaskQuery taskQuery = new TaskQueryMock().forService(taskService).count(5); 75 | 76 | assertThat(taskService.createTaskQuery().active().processDefinitionKey("foo").count()).isEqualTo(5); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/service/CaseServiceStubbingTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.service; 2 | 3 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 4 | import org.camunda.bpm.engine.CaseService; 5 | import org.camunda.community.mockito.ServiceExpressions; 6 | import org.junit.Test; 7 | 8 | import java.util.UUID; 9 | 10 | import static io.holunda.camunda.bpm.data.CamundaBpmData.booleanVariable; 11 | import static io.holunda.camunda.bpm.data.CamundaBpmData.stringVariable; 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | import static org.mockito.Mockito.mock; 14 | 15 | /** 16 | * Test to for case service variable access. 17 | */ 18 | public class CaseServiceStubbingTest { 19 | private static final VariableFactory ORDER_ID = stringVariable("orderId"); 20 | private static final VariableFactory ORDER_FLAG = booleanVariable("orderFlag"); 21 | 22 | @Test 23 | public void stubs_variable_access() { 24 | 25 | final CaseService caseService = mock(CaseService.class); 26 | final CaseServiceAwareService serviceUnderTest = new CaseServiceAwareService(caseService); 27 | 28 | String executionId = UUID.randomUUID().toString(); 29 | 30 | ServiceExpressions.caseServiceVariableStubBuilder(caseService) 31 | .defineAndInitializeLocal(ORDER_ID, "initial-Value") 32 | .define(ORDER_FLAG) 33 | .build(); 34 | 35 | serviceUnderTest.writeLocalId(executionId, "4712"); 36 | String orderId = serviceUnderTest.readLocalId(executionId); 37 | assertThat(orderId).isEqualTo("4712"); 38 | 39 | assertThat(serviceUnderTest.flagExists(executionId)).isFalse(); 40 | serviceUnderTest.writeFlag(executionId, true); 41 | assertThat(serviceUnderTest.flagExists(executionId)).isTrue(); 42 | Boolean orderFlag = serviceUnderTest.readFlag(executionId); 43 | assertThat(orderFlag).isEqualTo(true); 44 | } 45 | 46 | 47 | static class CaseServiceAwareService { 48 | private final CaseService caseService; 49 | 50 | CaseServiceAwareService(CaseService caseService) { 51 | this.caseService = caseService; 52 | } 53 | 54 | public String readLocalId(String executionId) { 55 | return ORDER_ID.from(caseService, executionId).getLocal(); 56 | } 57 | 58 | public void writeLocalId(String executionId, String value) { 59 | ORDER_ID.on(caseService, executionId).setLocal(value); 60 | } 61 | 62 | public void writeFlag(String executionId, Boolean value) { 63 | ORDER_FLAG.on(caseService, executionId).set(value); 64 | } 65 | 66 | public Boolean readFlag(String executionId) { 67 | return ORDER_FLAG.from(caseService, executionId).get(); 68 | } 69 | 70 | public Boolean flagExists(String executionId) { 71 | return caseService.getVariables(executionId).containsKey(ORDER_FLAG.getName()); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/service/RuntimeServiceStubbingTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.service; 2 | 3 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 4 | import org.camunda.bpm.engine.RuntimeService; 5 | import org.camunda.community.mockito.ServiceExpressions; 6 | import org.camunda.community.mockito.verify.RuntimeServiceVerification; 7 | import org.junit.Test; 8 | 9 | import java.util.UUID; 10 | 11 | import static io.holunda.camunda.bpm.data.CamundaBpmData.booleanVariable; 12 | import static io.holunda.camunda.bpm.data.CamundaBpmData.stringVariable; 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | import static org.mockito.Mockito.mock; 15 | import static org.mockito.Mockito.times; 16 | 17 | /** 18 | * Test to for runtime service variable access. 19 | */ 20 | public class RuntimeServiceStubbingTest { 21 | private static final VariableFactory ORDER_ID = stringVariable("orderId"); 22 | private static final VariableFactory ORDER_FLAG = booleanVariable("orderFlag"); 23 | 24 | 25 | @Test 26 | public void stubs_variable_access() { 27 | 28 | final RuntimeService runtimeService = mock(RuntimeService.class); 29 | final RuntimeServiceAwareService serviceUnderTest = new RuntimeServiceAwareService(runtimeService); 30 | 31 | String executionId = UUID.randomUUID().toString(); 32 | 33 | ServiceExpressions.runtimeServiceVariableStubBuilder(runtimeService) 34 | .defineAndInitializeLocal(ORDER_ID, "initial-Value") 35 | .define(ORDER_FLAG) 36 | .build(); 37 | 38 | serviceUnderTest.writeLocalId(executionId, "4712"); 39 | String orderId = serviceUnderTest.readLocalId(executionId); 40 | assertThat(orderId).isEqualTo("4712"); 41 | 42 | assertThat(serviceUnderTest.flagExists(executionId)).isFalse(); 43 | serviceUnderTest.writeFlag(executionId, true); 44 | assertThat(serviceUnderTest.flagExists(executionId)).isTrue(); 45 | Boolean orderFlag = serviceUnderTest.readFlag(executionId); 46 | assertThat(orderFlag).isEqualTo(true); 47 | } 48 | 49 | @Test 50 | public void verify_variable_access() { 51 | 52 | // setup mock 53 | final RuntimeService runtimeService = mock(RuntimeService.class); 54 | final RuntimeServiceAwareService serviceUnderTest = new RuntimeServiceAwareService(runtimeService); 55 | final RuntimeServiceVerification verifier = ServiceExpressions.runtimeServiceVerification(runtimeService); 56 | 57 | String executionId = UUID.randomUUID().toString(); 58 | ServiceExpressions.runtimeServiceVariableStubBuilder(runtimeService) 59 | .defineAndInitializeLocal(ORDER_ID, "initial-Value") 60 | .define(ORDER_FLAG) 61 | .build(); 62 | 63 | 64 | // execute service calls and check results 65 | serviceUnderTest.writeLocalId(executionId, "4712"); 66 | String orderId = serviceUnderTest.readLocalId(executionId); 67 | assertThat(orderId).isEqualTo("4712"); 68 | 69 | assertThat(serviceUnderTest.flagExists(executionId)).isFalse(); 70 | serviceUnderTest.writeFlag(executionId, true); 71 | assertThat(serviceUnderTest.flagExists(executionId)).isTrue(); 72 | Boolean orderFlag = serviceUnderTest.readFlag(executionId); 73 | assertThat(orderFlag).isEqualTo(true); 74 | 75 | // verify service access 76 | verifier.verifySetLocal(ORDER_ID, "4712", executionId ); 77 | verifier.verifyGetLocal(ORDER_ID, executionId); 78 | verifier.verifyGetVariables(executionId, times(2)); 79 | verifier.verifySet(ORDER_FLAG, true, executionId); 80 | verifier.verifyGet(ORDER_FLAG, executionId); 81 | verifier.verifyNoMoreInteractions(); 82 | 83 | } 84 | 85 | 86 | static class RuntimeServiceAwareService { 87 | private final RuntimeService runtimeService; 88 | 89 | RuntimeServiceAwareService(RuntimeService runtimeService) { 90 | this.runtimeService = runtimeService; 91 | } 92 | 93 | public String readLocalId(String execution) { 94 | return ORDER_ID.from(runtimeService, execution).getLocal(); 95 | } 96 | 97 | public void writeLocalId(String execution, String value) { 98 | ORDER_ID.on(runtimeService, execution).setLocal(value); 99 | } 100 | 101 | public void writeFlag(String execution, Boolean value) { 102 | ORDER_FLAG.on(runtimeService, execution).set(value); 103 | } 104 | 105 | public Boolean readFlag(String execution) { 106 | return ORDER_FLAG.from(runtimeService, execution).get(); 107 | } 108 | 109 | public Boolean flagExists(String execution) { 110 | return runtimeService.getVariables(execution).containsKey(ORDER_FLAG.getName()); 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/service/TaskServiceStubbingTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.service; 2 | 3 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 4 | import org.camunda.bpm.engine.TaskService; 5 | import org.camunda.community.mockito.ServiceExpressions; 6 | import org.junit.Test; 7 | 8 | import java.util.UUID; 9 | 10 | import static io.holunda.camunda.bpm.data.CamundaBpmData.booleanVariable; 11 | import static io.holunda.camunda.bpm.data.CamundaBpmData.stringVariable; 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | import static org.mockito.Mockito.mock; 14 | 15 | /** 16 | * Test to for task service variable access. 17 | */ 18 | public class TaskServiceStubbingTest { 19 | private static final VariableFactory ORDER_ID = stringVariable("orderId"); 20 | private static final VariableFactory ORDER_FLAG = booleanVariable("orderFlag"); 21 | 22 | private final TaskService taskService = mock(TaskService.class); 23 | private final MyTaskRestController myTaskRestController = new MyTaskRestController(taskService); 24 | 25 | @Test 26 | public void stubs_variable_access() { 27 | 28 | String taskId = UUID.randomUUID().toString(); 29 | 30 | ServiceExpressions.taskServiceVariableStubBuilder(taskService) 31 | .defineAndInitializeLocal(ORDER_ID, "initial-Value") 32 | .define(ORDER_FLAG) 33 | .build(); 34 | 35 | myTaskRestController.writeLocalId(taskId, "4712"); 36 | String orderId = myTaskRestController.readLocalId(taskId); 37 | assertThat(orderId).isEqualTo("4712"); 38 | 39 | assertThat(myTaskRestController.flagExists(taskId)).isFalse(); 40 | myTaskRestController.writeFlag(taskId, true); 41 | assertThat(myTaskRestController.flagExists(taskId)).isTrue(); 42 | Boolean orderFlag = myTaskRestController.readFlag(taskId); 43 | assertThat(orderFlag).isEqualTo(true); 44 | } 45 | 46 | 47 | static class MyTaskRestController { 48 | private final TaskService taskService; 49 | 50 | MyTaskRestController(TaskService taskService) { 51 | this.taskService = taskService; 52 | } 53 | 54 | public String readLocalId(String taskId) { 55 | return ORDER_ID.from(taskService, taskId).getLocal(); 56 | } 57 | 58 | public void writeLocalId(String taskId, String value) { 59 | ORDER_ID.on(taskService, taskId).setLocal(value); 60 | } 61 | 62 | public void writeFlag(String taskId, Boolean value) { 63 | ORDER_FLAG.on(taskService, taskId).set(value); 64 | } 65 | 66 | public Boolean readFlag(String taskId) { 67 | return ORDER_FLAG.from(taskService, taskId).get(); 68 | } 69 | 70 | public Boolean flagExists(String taskId) { 71 | return taskService.getVariables(taskId).containsKey(ORDER_FLAG.getName()); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/spring/SpringListeners.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.spring; 2 | 3 | import static org.assertj.core.api.Assertions.fail; 4 | 5 | import org.camunda.bpm.engine.delegate.DelegateExecution; 6 | import org.camunda.bpm.engine.delegate.ExecutionListener; 7 | import org.springframework.stereotype.Component; 8 | import org.springframework.stereotype.Service; 9 | 10 | public abstract class SpringListeners implements ExecutionListener { 11 | 12 | @Override 13 | public void notify(DelegateExecution delegateExecution) throws Exception { 14 | fail(this.getClass().getSimpleName() + ": not implemented!"); 15 | } 16 | 17 | @Component 18 | public static class SpringComponentListener extends SpringListeners {}; 19 | 20 | @Component("namedComponent") 21 | public static class SpringNamedComponentListener extends SpringListeners {}; 22 | 23 | @Service 24 | public static class SpringServiceListener extends SpringListeners {}; 25 | 26 | @Service("namedService") 27 | public static class SpringNamedServiceListener extends SpringListeners {}; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/task/LockedExternalTaskFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.task; 2 | 3 | import io.holunda.camunda.bpm.data.CamundaBpmData; 4 | import io.holunda.camunda.bpm.data.factory.VariableFactory; 5 | import io.holunda.camunda.bpm.data.reader.VariableReader; 6 | import org.camunda.bpm.engine.variable.Variables; 7 | import org.junit.Test; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | 11 | public class LockedExternalTaskFakeTest { 12 | 13 | private final VariableFactory var1 = CamundaBpmData.stringVariable("var1"); 14 | private final VariableFactory var2 = CamundaBpmData.stringVariable("var2"); 15 | 16 | @Test 17 | public void create_locked_task() { 18 | LockedExternalTaskFake fake = LockedExternalTaskFake.builder() 19 | .id("1") 20 | .activityId("foo") 21 | .variables(Variables.putValue("var2", "world")) 22 | .variable(var1, "hello") 23 | .build(); 24 | 25 | assertThat(fake.getId()).isEqualTo("1"); 26 | assertThat(fake.getActivityId()).isEqualTo("foo"); 27 | 28 | final VariableReader reader = CamundaBpmData.reader(fake.getVariables()); 29 | 30 | assertThat(reader.get(var1)).isEqualTo("hello"); 31 | assertThat(reader.get(var2)).isEqualTo("world"); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/typedvalues/VariableContextFakeTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.typedvalues; 2 | 3 | 4 | import org.camunda.bpm.engine.variable.VariableMap; 5 | import org.camunda.bpm.engine.variable.Variables; 6 | import org.junit.Test; 7 | 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | 10 | public class VariableContextFakeTest { 11 | 12 | private final VariableContextFake fake = new VariableContextFake(); 13 | 14 | @Test 15 | public void can_add_to_fake() { 16 | assertThat(fake.keySet()).isEmpty(); 17 | assertThat(fake.containsVariable("foo")).isFalse(); 18 | assertThat(fake.resolve("foo")).isNull(); 19 | 20 | fake.add("foo", Variables.booleanValue(false)); 21 | 22 | assertThat(fake.keySet()).containsOnly("foo"); 23 | assertThat(fake.containsVariable("foo")).isTrue(); 24 | assertThat(fake.resolve("foo")).isEqualTo(Variables.booleanValue(false)); 25 | } 26 | 27 | @Test 28 | public void to_variableMap() { 29 | fake.add("bar", Variables.stringValue("foo")); 30 | fake.add("foo", Variables.stringValue("bar")); 31 | 32 | VariableMap map = fake.get(); 33 | 34 | assertThat(map.getValue("foo", String.class)).isEqualTo("bar"); 35 | assertThat(map.getValue("bar", String.class)).isEqualTo("foo"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/test/java/org/camunda/community/mockito/verify/MockitoVerificationTest.java: -------------------------------------------------------------------------------- 1 | package org.camunda.community.mockito.verify; 2 | 3 | import static org.mockito.Mockito.times; 4 | import static org.mockito.MockitoAnnotations.initMocks; 5 | 6 | import org.camunda.bpm.engine.delegate.DelegateExecution; 7 | import org.camunda.community.mockito.DelegateExpressions; 8 | import org.camunda.community.mockito.mock.FluentJavaDelegateMock; 9 | import org.junit.Before; 10 | import org.junit.Test; 11 | import org.mockito.Mock; 12 | 13 | public class MockitoVerificationTest { 14 | 15 | private static final String JAVA_DELEGATE = "javaDelegate"; 16 | 17 | private final FluentJavaDelegateMock javaDelegate = DelegateExpressions.registerJavaDelegateMock(JAVA_DELEGATE); 18 | 19 | @Mock 20 | private DelegateExecution delegateExecution; 21 | 22 | @Before 23 | public void setUp() throws Exception { 24 | initMocks(this); 25 | } 26 | 27 | @Test 28 | public void shouldVerifyExecuteCalled() throws Exception { 29 | javaDelegate.execute(delegateExecution); 30 | 31 | DelegateExpressions.verifyJavaDelegateMock(JAVA_DELEGATE).executed(); 32 | } 33 | 34 | @Test 35 | public void shouldVerifyExecuteCalledTwice() throws Exception { 36 | javaDelegate.execute(delegateExecution); 37 | javaDelegate.execute(delegateExecution); 38 | 39 | DelegateExpressions.verifyJavaDelegateMock(JAVA_DELEGATE).executed(times(2)); 40 | } 41 | 42 | @Test 43 | public void shouldVerifyExecuteNotCalled() throws Exception { 44 | DelegateExpressions.verifyJavaDelegateMock(JAVA_DELEGATE).executedNever(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/test/resources/process_with_callActivity_binding_deployment.bpmn: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Flow_0dyug1t 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Flow_0dyug1t 14 | Flow_1mtklbt 15 | 16 | 17 | Flow_1mtklbt 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/test/resources/simplelogger.properties: -------------------------------------------------------------------------------- 1 | org.slf4j.simpleLogger.defaultLogLevel = info 2 | org.slf4j.simpleLogger.showShortLogName = false 3 | org.slf4j.simpleLogger.levelInBrackets = true 4 | 5 | org.slf4j.simpleLogger.log.org.camunda.bpm.engine.persistence = WARN 6 | org.slf4j.simpleLogger.log.org.camunda.feel.FeelEngine = WARN 7 | org.slf4j.simpleLogger.log.org.camunda.bpm.engine.context = WARN 8 | --------------------------------------------------------------------------------