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.
Join the DZone community and get the full member experience.
Join For FreeWriting 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.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments