Suche

1. What You Will Learn

In this guide you will learn how to write UnitTests for Java Commands with LiteService and
InjectService. InjectService allows you to implement a Service within another Service.

2. Prerequisites

To complete this guide you need:

  • Roughly 10 minutes

  • JDK11+ installed with JAVA_HOME configured appropriately

  • An IDE (we recommend IntelliJ)

  • Some kind of build tool (like Gradle, Maven or Apache Ant)

  • Read the UnitTest Java Command with Service guide

  • JUnit 5 environment

3. Dependencies

To write UnitTests for a Command we need to include some dependencies:

Dependencies Reason to include

de.asap.pak.jlcint:jlcint-commandapi

Provides annotations used to develop a Java Command

de.asap.pak.jlcint:jlcint-testutils

Utilities that allow the testing of Java Commands

de.asap.pak.core:pak-context

Contains the @InjectService annotation

org.junit.jupiter:junit-jupiter

Allows the writing of JUnit5 tests

org.junit.jupiter:junit-jupiter-engine

org.mockito:mockito-inline

Allows the simulation of not implemented interfaces from other components by using mock objects instead

org.mockito:mockito-junit-jupiter

4. The UnitTest

We want to test the Java Command we have written in the PAK Service Based Command guide.

4.1. @LiteService

The @LiteService annotation basically works like @Service. A LiteService is in fact a class that
implements the marker-interface ILiteService. The respective class is mostly located in the same Java
module like the Command itself.

4.2. @InjectService

@InjectService can be used for development inside the PAK-framework. Only Services registered within
IServiceProvider, or the ServiceLoader should be annotated by this annotation. Therefore, Services
from these instances can be injected into the Service, using @InjectService, so they can access the
Services themselves easily.

4.3. UnitTest with LiteService and InjectService

Command Class Test Class
/**
 * @workflowDocu Simple command that resolves a given JSON path for the
 * given JSON string.
 */
@JavaCommand
@CommandGroup("org.example")
public class ResolveJsonPath {
	/**
     * @workflowDocu Service which provides the ability to resolve JSON paths
     */
	@LiteService (2)
	private JsonPathService jsonService;

	/**
     * @workflowDocu The JSON string to look in
     */
	@Persistent
	private String jsonString;

	/**
     * @workflowDocu The JSON path to search
     */
	@Persistent
	private String jsonPath;

	/**
     * @workflowDocu Result of the operation
     */
	@Persistent(scope = FieldScope.WRITE_ONLY)
	private String resolvedPath;

	@Run
	public void resolveJsonPath() {
		this.resolvedPath = this.jsonService.fetchJsonPath(this.jsonString, this.jsonPath);
	}
}
@ExtendWith({ MockitoExtension.class, JlcintExtension.class }) (1)
class ResolveJsonPathTest {
    // Service which provides the ability to resolve JSON paths
	@LiteService (2)
	private JsonPathService jsonService;

	// Service which provides JSON mapper functionality
    @InjectService (3)
	private IJsonMapper jsonMapper;

	// The JSON string to look in
	@Persistent
	private String jsonString;

	// The JSON path to search
	@Persistent
	private String jsonPath;

	//Result of the operation
	@Persistent(scope = FieldScope.WRITE_ONLY)
	private String resolvedPath;

	//Provides the ability to run the command without a client
	private Provider<ResolveJsonPath> command;
}
/**
* Service class which provides JSON path functionality.
*/
public class JsonPathService implements ILiteService {
@InjectService (3)
private IJsonMapper jsonMapper;

    /**
     * Resolves a given JSON path in the given object using the Engine's json mapper.
     *
     * @param object Object to look in
     * @param path Path to look for
     * @return Resolved JSON path
     */
    public String fetchJsonPath(final String object, final String path) {
    	return this.jsonMapper.resolvePathIn(object, path.split("\\."));
    }
}
1 Additional to the JlcintExtension the MockitoExtension which is provided by the mockito-junit-jupiter dependency is needed. The MockitoExtension provides the ability to use the @Mock annotation.
2 The Service under test is annotated with @LiteService and is usually an interface of an adapter.
3 The inner Service is annotated with @InjectService.
The @Persistent-Annotation of the Command Fields need to be mirrored 1 to 1. For the
test class it is sufficient to have a simple annotation over the input and output fields. So
@Persistent and for output fields the scope will be enough.

4.4. UnitTest with Mocked Services

To test the ResolveJsonPath Command without the need to implement the LiteService and InjectService Services yourself, you can mock these services.
Keep in mind that this means that you have to test the functionality of your Services separately.

LiteService InjectService
@ExtendWith({ MockitoExtension.class, JlcintExtension.class })
class ResolveJsonPathTest {
	// Service which provides the ability to resolve JSON paths
	@LiteService
	@Mock
	private JsonPathService jsonService;

	// The JSON string to look in
	@Persistent
	private String jsonString;

	// The JSON path to search
	@Persistent
	private String jsonPath;

	//Result of the operation
	@Persistent(scope = FieldScope.WRITE_ONLY)
	private String resolvedPath;

	//Provides the ability to run the command without a client
	private Provider<ResolveJsonPath> command;

	@BeforeEach
	void setAttributes() {
		// Set attributes
		this.jsonString = "{\"variable1\": \"value1\", \"variable2\": \"value2\", \"variable3\": \"value3\"}";
		this.jsonPath = "variable1";
	}

	@Test
	void runResolveJsonPathTestLiteService() {

		Mockito.when(this.jsonService.fetchJsonPath(this.jsonString, this.jsonPath)).thenReturn("value1");

		assertDoesNotThrow(() -> this.command.execute());

		// Check the result of mocking test
		Mockito.verify(this.jsonService).fetchJsonPath(this.jsonString, this.jsonPath);
	}
}
@ExtendWith({ MockitoExtension.class, JlcintExtension.class })
class ResolveJsonPathServiceTest {
	// Service which provides the ability to resolve JSON paths
	@LiteService
	private JsonPathService jsonService;

	// Service which provides JSON mapper functionality
	@Mock
	@InjectService
	private IJsonMapper mockedJsonMapper;

	// The JSON string to look in
	@Persistent
	private String jsonString;

	// The JSON path to search
	@Persistent
	private String jsonPath;

	//Result of the operation
	@Persistent(scope = FieldScope.WRITE_ONLY)
	private String resolvedPath;

	//Provides the ability to run the command without a client
	private Provider<ResolveJsonPath> command;

	@BeforeEach
	void setAttributes() {
		// Set attributes
		this.jsonString = "{\"variable1\": \"value1\", \"variable2\": \"value2\", \"variable3\": \"value3\"}";
		this.jsonPath = "variable1";
	}

	@Test
	void runResolveJsonPathTestLiteService() {

		// Mock json Service (simple test implementation)
		this.jsonService = new JsonPathService();

		Mockito.when(this.mockedJsonMapper.resolvePathIn(this.jsonString, this.jsonPath.split("\\."))).thenReturn("value1");

		assertDoesNotThrow(() -> this.command.execute());

		// Check the result of mocking test
		Mockito.verify(this.mockedJsonMapper).resolvePathIn(this.jsonString, this.jsonPath.split("\\."));
	}
}
1 With this Mockito Command the real Service object will be replaced by a mock object.
2 The mock object is checked if it is called correctly with the predefined attributes.

Now you can run the test and see if the Command will be able to run in general.

5. Summary

In this guide we have learned how to write a UnitTest to run a Java Command using a LiteService with
an InjectService within.

Sonatype Nexus

PAK features connectors and commands for Sonatype Nexus. This means the software can directly interact with Nexus repositories for storing and managing artifacts. Through these connectors, PAK can automate tasks like uploading binaries or retrieving dependencies, ensuring efficient artifact management within Nexus.

Jenkins

PAK has connectors and commands for Jenkins. This allows the software to directly communicate with Jenkins servers, enabling the automation of CI/CD (Continuous Integration/Continuous Deployment) tasks. Through these connectors, PAK can trigger builds, fetch build statuses, or manage job configurations, streamlining the CI/CD processes within Jenkins.

Git Hub

PAK possesses connectors and commands for GitHub. This means the software can interface directly with GitHub repositories, facilitating actions like code pushes, pull requests, or issue tracking. Through these connectors, PAK can automate various GitHub operations, enhancing code collaboration and repository management.

Atlassian Confluence

PAK is equipped with connectors and commands for Atlassian Confluence. This enables the software to directly interact with Confluence spaces and pages. Through these connectors, PAK can automate actions such as creating, updating, or retrieving documentation, ensuring efficient content management and collaboration within Confluence.

Codebeamer

PAK features connectors and commands for Codebeamer. This allows the software to seamlessly integrate with Codebeamer’s ALM (Application Lifecycle Management) platform. Through these connectors, PAK can automate tasks like issue tracking, test management, or requirements tracing, enhancing the coordination and management of software development processes.

JFrog Artifactory

PAK has connectors and commands for JFrog Artifactory. This means the software can directly interface with Artifactory repositories, enabling actions like artifact storage, retrieval, and management. Through these connectors, PAK can automate tasks such as deploying artifacts or managing repository configurations, streamlining the integration and management of binary artifacts within Artifactory.

Amazon Web Services (AWS)

PAK has connectors and commands for Amazon Web Services (AWS). This means the software possesses specialized interfaces to directly interact with AWS services and execute actions on the AWS platform. Through these connectors, PAK can automate AWS-specific commands, such as launching EC2 instances, managing S3 buckets, or configuring Lambda functions. This allows for efficient integration, management, and automation of AWS resources and services directly from PAK.

Atlassian Jira

PAK features integration tools and capabilities for Atlassian Jira. These tools allow for a direct connection to Jira and the execution of specific actions. Using these integration tools, PAK can automate Jira actions such as adding comments or changing ticket priorities, ensuring seamless handling and coordination of Jira processes.

Git

PAK has connectors and commands for Git. This means it has interfaces to directly communicate with Git and execute actions. Through these connectors, the software can automate Git commands such as retrieving changes or creating branches, enabling efficient integration and management of Git tasks.

Generic Human Tasks

PAK offers you a standard set of commands which require creative input from the user. Enables you to start with automating your workflows, that still need abit of human input.

Generic Commands

PAK offers a standard set of commands giving you the first steps to automate your workflows.

Nexus Maven Command Pool

Nexus is an artifact repository manager for storing binaries, libraries, and artifacts, supporting formats like Maven. Maven, a software project management tool, is based on the Project Object Model (POM) and allows developers to consistently define projects and dependencies. Our Command Pool offers commands for interactions between Maven and Nexus, such as artifact uploads or dependency retrieval.

Artifactory Maven Command Pool

Artifactory allows developers to store, retrieve, and manage binary files and artifacts, providing a
central source for all binaries used in a development process. Apache Maven is a software project
management and comprehension tool that enables developers to consistently describe a project and
its dependencies. Our Command Pool offers a collection of commands used to facilitate interactions
between Maven and Artifactory, such as uploading artifacts or retrieving dependencies.

Open API Command Interpreter

The OpenApi Command Interpreter allows you the automatic parsing of commands from an OpenApi defintion. No additional code needs to be written anymore, just add the address to the definition and our framework does the rest!

Kotlin Command Interpreter

The Kotlin Command Interpreter allows you the parsing and execution of commands within a Kotlin environment to automate various tasks or processes.

Bpmn Interpreter

Workflows come in many shapes and forms. The BPMN (Business Process Model and Notation) Interpreter enables the parsing of worklows defined in the BPMN format into the PAK intern model.

Human Task Interpreter

The Human Task Interpreter allows you the parsing and running of commands within a HTML and Javascript environment. Use this to build commands which need the creative input of a workflow user!

Java Command Interpreter

The Java Command Interpreter allows you the parsing and execution of commands within a Java
environment to automate various tasks or processes.

Core

The heart of the PAK-Framework. Contains the means to run workflows with the PAK engine, but also the possibility to enrich the frameworks interfaces with your own implementations and solutions.

RocksDB Persistence

Data that is generated by a workflow run needs to be saved for short or longer terms. Our solution to the Persistence Interface of the PAK-Framework is to use the high-performance, key-value based RocksDB developed by Facebook.

PAK online

PAK Online is a web based application and provides an Open API based REST API. It enables you to upload workflows and run them periodically or on REST demand.

Command Line App

Run tasks and workflows on the console or as part of a CI/CD Pipeline with our Command Line Interface.

Workflow Editor

With our specially developed editor, a wide variety of workflows can be easily modeled in the wide known BPMN process format.

Workflow Executor

The Workflow Executor is the application to run your workflows. It features a multilingual UI and easy managment of your favorite workflows.

Support

We offer a community website where you can exchange ideas and support each other. For our Pro packages we also offer full support via email.