DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Cypress.io — The Rising Future of Web Automation Testing
  • Advanced Error Handling in JavaScript
  • Mastering macOS Client-Server Application Testing: Tools and Key Differences
  • Enhancing Testing Efficiency: Transitioning From Traditional Code Coverage to Code Change Coverage

Trending

  • Observability for Agents and Workflows: Tracing Prompts, Tool Calls, and Business Outcomes End-to-End
  • Why Stable RAG Answers Can Still Hide Unstable Evidence
  • Implementing Secure API Gateways for Microservices Architecture
  • Liquid Glass, Material 3, and a Lot of Plumbing
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Micronaut Mastery: Using Stubs for Testing

Micronaut Mastery: Using Stubs for Testing

Micronaut is a framework for easily writing microservices. Let's discover how to use it to write stubs for testing in this tutorial.

By 
Hubert Klein Ikkink user avatar
Hubert Klein Ikkink
·
Aug. 29, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
8.4K Views

Join the DZone community and get the full member experience.

Join For Free

Writing tests is always a good idea when developing an application. Micronaut makes it very easy to write tests. Using the @Client annotation we can generate a client for our REST resources that uses HTTP. Starting up a Micronaut application is so fast we can run our actual application in our tests. And using dependency injection we can replace components from the production application with stubs in our tests.

Let's show how we can use stub in our tests for an example application. In the example application, we have a controller ConferenceController that returns Conference objects. These objects are fetched from a simple data repository, ConferenceDataRepository. When we write a test, we want to replace the ConferenceDataRepository with a stub so we can return the appropriate Conference objects for our tests.

First, we take a look at the Conference class:

package mrhaki.micronaut;

public class Conference {

    private final String name;
    private final String location;

    public Conference(String name, String location) {
        this.name = name;
        this.location = location;
    }

    public String getName() {
        return name;
    }

    public String getLocation() {
        return location;
    }

}

We add an interface that describes the functionality we expect for getting Conference objects in our application:

// File: src/main/java/mrhaki/micronaut/ConferenceService.java
package mrhaki.micronaut;

import io.reactivex.Maybe;
import io.reactivex.Single;

import java.util.List;

interface ConferenceService {

    Single<List<Conference>> all();

    Maybe<Conference> findByName(final String name);

}

For our example, the implementation of the ConferenceService is simple, but in a real-world application, the code would probably access a database to get the results:

// File: src/main/java/mrhaki/micronaut/ConferenceDataRepository.java
package mrhaki.micronaut;

import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.Single;

import javax.inject.Singleton;
import java.util.Arrays;
import java.util.List;

@Singleton
public class ConferenceDataRepository implements ConferenceService {

    private final static List<Conference> CONFERENCES =
            Arrays.asList(new Conference("Gr8Conf EU", "Copenhagen"),
                          new Conference("Gr8Conf US", "Minneapolis"),
                          new Conference("Greach", "Madrid"));

    public Single<List<Conference>> all() {
        return Single.just(CONFERENCES);
    }

    public Maybe<Conference> findByName(final String name) {
        return all()
                .flatMapObservable(conferences -> Observable.fromIterable(conferences))
                .filter(conference -> name.equals(conference.getName()))
                .singleElement();
    }

}

Finally, our controller returns conference data via HTTP REST that uses, via dependency injection, the ConferenceDataRepository implementation of the ConferenceService interface:

// File: src/main/java/mrhaki/micronaut/ConferenceController.java
package mrhaki.micronaut;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.reactivex.Maybe;
import io.reactivex.Single;

import java.util.List;

@Controller("/conference")
public class ConferenceController {

    private final ConferenceService conferenceService;

    public ConferenceController(final ConferenceService conferenceService) {
        this.conferenceService = conferenceService;
    }

    @Get("/")
    public Single<List<Conference>> all() {
        return conferenceService.all();
    }

    @Get("/{name}")
    public Maybe<Conference> findByName(final String name) {
        return conferenceService.findByName(name);
    }

}

To add a stub for the ConferenceService in our test, we must write a new implementation of the ConferenceService that is available on the test classpath and not on the production code classpath. In our test code directory (src/test/{java|groovy|kotlin}) we write our stub implementation. We use the @Primary annotation to instruct Micronaut to use this implementation of the ConferenceService interface. If we leave out the @Primary annotation, we get an error because we have two implementations of the interface on our classpath, ConferenceDataRepository and ConferenceServiceStub, and Micronaut doesn't know which one to use. By using @Primary, we tell Micronaut to use the stub implementation.

// File: src/test/groovy/mrhaki/micronaut/ConferenceServiceStub.groovy
package mrhaki.micronaut

import io.micronaut.context.annotation.Primary
import io.reactivex.Maybe
import io.reactivex.Single

import javax.inject.Singleton

@Singleton
@Primary
class ConferenceServiceStub implements ConferenceService {

    Single<List<Conference>> all() {
        return Single.just([new Conference("Gr8Conf", "Copenhagen")])
    }

    Maybe<Conference> findByName(final String name) {
        if (name == 'Gr8Conf') {
            return Maybe.just(new Conference("Gr8Conf", "Copenhagen"))
        } else {
            return Maybe.empty()
        }
    }

}

In our test directory, we also add a declarative HTTP client to invoke the REST resource. This client is only used for testing and makes invoking the REST resource very easy:

// File: src/test/groovy/mrhaki/micronaut/ConferenceClient.groovy
package mrhaki.micronaut

import io.micronaut.http.annotation.Get
import io.micronaut.http.client.Client
import io.reactivex.Maybe
import io.reactivex.Single

@Client("/conference")
interface ConferenceClient {

    @Get("/")
    Single<List<Conference>> all()

    @Get("/{name}")
    Maybe<Conference> findByName(final String name)

}

We write a Spock specification to test our REST resource and it will use the stub code as implementation of ConferenceService:

// File: src/test/groovy/mrhaki/micronaut/ConferenceContollerSpec.groovy
package mrhaki.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.runtime.server.EmbeddedServer
import io.reactivex.Maybe
import io.reactivex.Single
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class ConferenceContollerSpec extends Specification {

    @Shared
    @AutoCleanup
    private EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer)

    @Shared
    private ConferenceClient client = embeddedServer.applicationContext.getBean(ConferenceClient)

    void 'get all conferences'() {
        when:
        final Single<List<Conference>> result = client.all()

        then:
        final conference = result.blockingGet().first() 
        with(conference) {
            name == 'Gr8Conf'
            location == 'Copenhagen'
        }
    }

    void 'find conference by name'() {
        when:
        final Maybe<Conference> result = client.findByName('Gr8Conf')

        then:
        final conference = result.blockingGet()
        with(conference) {
            name == 'Gr8Conf'
            location == 'Copenhagen'
        }
    }

    void 'return empty when conference cannot be found by name'() {
        when:
        final Maybe<Conference> result = client.findByName('JavaOne')

        then:
        result.isEmpty().blockingGet()
    }
}

Written with Micronaut 1.0.0.M4.

Stub (distributed computing) application Testing Implementation

Published at DZone with permission of Hubert Klein Ikkink. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Cypress.io — The Rising Future of Web Automation Testing
  • Advanced Error Handling in JavaScript
  • Mastering macOS Client-Server Application Testing: Tools and Key Differences
  • Enhancing Testing Efficiency: Transitioning From Traditional Code Coverage to Code Change Coverage

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook