Skip to content

microcks/microcks-testcontainers-java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Microcks Testcontainers Java

Java library for Testcontainers that enables embedding Microcks into your JUnit tests with lightweight, throwaway instance thanks to containers

GitHub Workflow Status Version License Project Chat

Build Status

Latest released version is 0.2.8.

Current development version is 0.2.9-SNAPSHOT.

Sonarcloud Quality metrics

Code Smells Reliability Rating Bugs Coverage Technical Debt Security Rating Maintainability Rating

How to use it?

Include it into your project dependencies

If you're using Maven:

<dependency>
  <groupId>io.github.microcks</groupId>
  <artifactId>microcks-testcontainers</artifactId>
  <version>0.2.8</version>
</dependency>

or if you're using Gradle:

dependencies {
    testImplementation 'io.github.microcks:microcks-testcontainers:0.2.8'
}

Startup the container

You just have to specify the container image you'd like to use. This library requires a Microcks uber distribution (with no MongoDB dependency).

Version 0.2.1 and above require version 1.8.1 of Microcks container images.

MicrocksContainer microcks = new MicrocksContainer(
      DockerImageName.parse("quay.io/microcks/microcks-uber:1.9.0"));
microcks.start();

Import content in Microcks

To use Microcks mocks or contract-testing features, you first need to import OpenAPI, Postman Collection, GraphQL or gRPC artifacts. Artifacts can be imported as main/Primary ones or as secondary ones. See Multi-artifacts support for details.

You can do it before starting the container using simple paths:

MicrocksContainer microcks = new MicrocksContainer(DockerImageName.parse("quay.io/microcks/microcks-uber:1.9.0"))
    .withMainArtifacts("apipastries-openapi.yaml")
    .withSecondaryArtifacts("apipastries-postman-collection.json");
microcks.start();

or once the container started using File arguments:

microcks.importAsMainArtifact(new File("target/test-classes/apipastries-openapi.yaml"));
microcks.importAsSecondaryArtifact(new File("target/test-classes/apipastries-postman-collection.json"));

Please refer to our MicrocksContainerTest for comprehensive example on how to use it.

Starting with version 0.2.7 you can also import full repository snapshots at once:

MicrocksContainer microcks = new MicrocksContainer(DockerImageName.parse("quay.io/microcks/microcks-uber:1.9.0"))
      .withSnapshots("microcks-repository.json");
microcks.start();

Using mock endpoints for your dependencies

During your test setup, you'd probably need to retrieve mock endpoints provided by Microcks containers to setup your base API url calls. You can do it like this:

String baseApiUrl = microcks.getRestMockEndpoint("API Pastries", "0.0.1");

The container provides methods for different supported API styles/protocols (Soap, GraphQL, gRPC,...).

The container also provides getHttpEndpoint() for raw access to those API endpoints.

Launching new contract-tests

If you want to ensure that your application under test is conformant to an OpenAPI contract (or other type of contract), you can launch a Microcks contract/conformance test using the local server port you're actually running. This is typically how it could be done for a Spring Boot application:

@LocalServerPort
private Integer port;

@BeforeEach
public void setupPort() {
   // Host port exposition should be done here.
   Testcontainers.exposeHostPorts(port);
}

@Test
public void testOpenAPIContract() throws Exception {
    // Ask for an Open API conformance to be launched.
    TestRequest testRequest = new TestRequest.Builder()
        .serviceId("API Pastries:0.0.1")
        .runnerType(TestRunnerType.OPEN_API_SCHEMA.name())
        .testEndpoint("http://host.testcontainers.internal:" + port)
        .timeout(Duration.ofSeconds(2))
        .build();

    TestResult testResult = microcks.testEndpoint(testRequest);
    assertTrue(testResult.isSuccess());
}

The TestResult gives you access to all details regarding success of failure on different test cases.

A comprehensive Spring Boot demo application illustrating both usages is available here: spring-boot-order-service.

Using authentication Secrets

It's a common need to authenticate to external systems like Http/Git repositories or external brokers. For that, the MicrocksContainer provides the withSecret() method to register authentication secrets at startup:

microcks.withSecret(new Secret.Builder()
      .name("localstack secret")
      .username(localstack.getAccessKey())
      .password(localstack.getSecretKey())
      .build());
microcks.start();

You may reuse this secret using its name later on during a test like this:

TestRequest testRequest = new TestRequest.Builder()
      .serviceId("Pastry orders API:0.1.0")
      .runnerType(TestRunnerType.ASYNC_API_SCHEMA.name())
      .testEndpoint("sqs://eu-east-1/pastry-orders?overrideUrl=http://localstack:45566")
      .secretName("localstack secret")
      .timeout(5000L)
      .build();

Advanced features with MicrocksContainersEnsemble

The MicrocksContainer referenced above supports essential features of Microcks provided by the main Microcks container. The list of supported features is the following:

  • Mocking of REST APIs using different kinds of artifacts,
  • Contract-testing of REST APIs using OPEN_API_SCHEMA runner/strategy,
  • Mocking and contract-testing of SOAP WebServices,
  • Mocking and contract-testing of GraphQL APIs,
  • Mocking and contract-testing of gRPC APIs.

To support features like Asynchronous API and POSTMAN contract-testing, we introduced MicrocksContainersEnsemble that allows managing additional Microcks services. MicrocksContainersEnsemble allow you to implement Different levels of API contract testing in the Inner Loop with Testcontainers!

A MicrocksContainersEnsemble conforms to Testcontainers lifecycle methods and presents roughly the same interface as a MicrocksContainer. You can create and build an ensemble that way:

MicrocksContainersEnsemble ensemble = new MicrocksContainersEnsemble(IMAGE)
    .withMainArtifacts("apipastries-openapi.yaml")
    .withSecondaryArtifacts("apipastries-postman-collection.json")
    .withAccessToHost(true);
ensemble.start();

A MicrocksContainer is wrapped by an ensemble and is still available to import artifacts and execute test methods. You have to access it using:

MicrocksContainer microcks = ensemble.getMicrocksContainer();
microcks.importAsMainArtifact(...);
microcks.getLogs();

Please refer to our MicrocksContainerTest for comprehensive example on how to use it.

Postman contract-testing

On this ensemble you may want to enable additional features such as Postman contract-testing:

ensemble.withPostman();
ensemble.start();

You can execute a POSTMAN test using an ensemble that way:

TestRequest testRequest = new TestRequest.Builder()
    .serviceId("API Pastries:0.0.1")
    .runnerType(TestRunnerType.POSTMAN.name())
    .testEndpoint("http://good-impl:3003")
    .timeout(2500L)
    .build();

TestResult testResult = ensemble.getMicrocksContainer().testEndpoint(testRequest);

Asynchronous API support

Asynchronous API feature need to be explicitly enabled as well. In the case you want to use it for mocking purposes, you'll have to specify additional connection details to the broker of your choice. See an example below with connection to a Kafka broker:

ensemble.withAsyncFeature()
      .withKafkaConnection(new KafkaConnection("kafka:9092"));
ensemble.start();
Using mock endpoints for your dependencies

Once started, the ensemble.getAsyncMinionContainer() provides methods for retrieving mock endpoint names for the different supported protocols (WebSocket, Kafka, SQS and SNS).

String kafkaTopic = ensemble.getAsyncMinionContainer()
      .getKafkaMockTopic("Pastry orders API", "0.1.0", "SUBSCRIBE pastry/orders");
Launching new contract-tests

Using contract-testing techniques on Asynchronous endpoints may require a different style of interacting with the Microcks container. For example, you may need to:

  1. Start the test making Microcks listen to the target async endpoint,
  2. Activate your System Under Tests so that it produces an event,
  3. Finalize the Microcks tests and actually ensure you received one or many well-formed events.

For that the MicrocksContainer now provides a testEndpointAsync(TestRequest request) method that actually returns a CompletableFuture. Once invoked, you may trigger your application events and then get() the future result to assert like this:

// Start the test, making Microcks listen the endpoint provided in testRequest
CompletableFuture<TestResult> testResultFuture = ensemble.getMicrocksContainer().testEndpointAsync(testRequest);

// Here below: activate your app to make it produce events on this endpoint.
// myapp.invokeBusinessMethodThatTriggerEvents();
      
// Now retrieve the final test result and assert.
TestResult testResult = testResultFuture.get();
assertTrue(testResult.isSuccess());

About

Java lib for Testcontainers that enables embedding Microcks into your JUnit tests with lightweight, throwaway instance thanks to containers.

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Languages