Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Unit Testing vs. Component Testing in Lagom

DZone's Guide to

Unit Testing vs. Component Testing in Lagom

Using Lagom to reduce your boilerplate code? See how component and unit testing apply to Lagom and how to approach both.

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Let’s begin with the basic differences between unit testing and component testing, and then we will have a look at a practical application of unmanaged services in Lagom with its test cases.

Unit Testing and Component Testing

Unit testing involves the testing of individual units (classes) to demonstrate that the program executes as per the specification and that it validates the design and technical quality of that particular unit. The called components are replaced with stubs, simulators, or trusted components that are used to simulate the behavior of interfacing modules.

On the other hand, component testing will test the system without other third-party code and services. Thus, it verifies and validates the functionality and performance of a particular component. This testing is limited to that particular component only.

The basic difference between the two is that in unit testing, all the methods of other classes and modules are mocked. On the other hand, for component testing, all stubs and simulators are replaced with the real objects for all the classes (units) of that component, and mocking is used for classes of other components.

Testing in Lagom is a little different from the way we test our code in Scala and Java.

In my perception, in order to unit test a service in Lagom, we should use an object of the impl class, whereas in component testing, a fake server should be started to make calls to our services and produce a result — so that we can assert it against the expected result.

Practical Application

Let’s look at a demo application, i.e. an unmanaged service in lagom that extracts user data.

It consists of three modules:

1. external-api

2. user-api

3. user-impl

Module 1: external-api

This module consists of an interface.

ExternalService

This is an unmanaged service that hits the external API and provides data. The URL of the unmanaged service used in the program is https://jsonplaceholder.typicode.com:443.

The data received is wrapped in an object of a class named UserData, which has the parameters userId, id, title, body.

The code snippet is given below:

public interface ExternalService extends Service {
    ServiceCall<NotUsed, UserData> getUser();
    @Override
    default Descriptor descriptor() {
        return Service.named("external-service").withCalls(
                Service.restCall(Method.GET, "/posts/1", this::getUser)
        ).withAutoAcl(true);
    }
}


Module 2: user-api

This module consists of an interface.

UserService

UserService consists of our ServiceCall named helloUser, which simply returns the userId from the unmanaged service.

public interface UserService extends Service{
    ServiceCall<NotUsed, UserResponse> helloUser();
    @Override
    default Descriptor descriptor(){
        return named("helloUser").withCalls(
                restCall(Method.GET,"/user",this::helloUser))
                .withAutoAcl(true);
    }
}


Module 3: user-impl

This module implements the UserService. It calls the getUser() method of the ExternalService. The UserData received is thus passed to the ResponseMapper class, which manipulates the data and returns an object of class UserResponse having a single field, i.e. message.

The code snippet for the UserModule is:

public class UserModule extends AbstractModule implements ServiceGuiceSupport {
    private final Environment environment;
    private final Configuration configuration; //NOSONAR as this is required field.
    public UserModule(Environment environment, Configuration configuration) {
        this.environment = environment;
        this.configuration = configuration;
    }
    @Override
    protected void configure() {
        bindService(UserService.class, UserServiceImpl.class);
        bindClient(ExternalService.class);
    }
}


The user-impl module further consists of two classes: UserServiceImpl and ResponseMapper

UserServiceImpl

public class UserServiceImpl implements UserService {
    @Inject
    ExternalService externalService;
    @Inject
    ResponseMapper responseMapper;
    public CompletionStage < UserData > hitAPI() {
        CompletionStage < UserData > userData = externalService
            .getUser()
            .invoke();
        return userData;
    }
    @Override
    public ServiceCall < NotUsed, UserResponse > helloUser() {
        return request - > {
            CompletionStage < UserData > userData = hitAPI();
            return userData.thenApply(
                userInfo - > {
                    UserResponse userResponse = responseMapper.getResponse(userInfo);
                    return userResponse;
                }
            );
        };
    }
}


ResponseMapper 

public class ResponseMapper {
    public UserResponse getResponse(UserData userData) {
        UserResponse userResponse = new UserResponse();
        userResponse.setMessage("Hello, Your UserId is " + userData.userId);
        return userResponse;
    }
}


Testing

I have used jMockit to test my application.

Unit Testing of UserServiceImpl

In order to write the unit test cases for UserSeviceImpl, an instance of the class is created and marked with the annotation @Tested. This instance should be used to call the method that has to be tested. All the methods of other classes and modules are mocked using Expectations. The code snippet is below: 

public class UserServiceImplTest {
    private static final Integer ID = 1;
    private static final Integer USERID = 1;
    private static final String TITLE = "title";
    private static final String BODY = "body";
    private static UserData newUserData = new UserData() {
        {
            setId(ID);
            setUserId(USERID);
            setTitle(TITLE);
            setBody(BODY);
        }
    };
    @SuppressWarnings("unused")
    @Tested
    private UserServiceImpl userServiceImpl;
    @SuppressWarnings("unused")
    @Injectable
    private ExternalService externalService;
    @SuppressWarnings("unused")
    @Injectable
    private ResponseMapper responseMapper;
    @Test
    public void helloUserTest() throws Exception {
        new Expectations() {
            {
                externalService.getUser();
                result = new ServiceCall<NotUsed, UserData>() {
                    @Override
                    public CompletionStage<UserData> invoke(NotUsed notUsed) {
                        return CompletableFuture.completedFuture(newUserData);
                    }
                };
            }
            {
                responseMapper.getResponse(newUserData);
                result = new UserResponse() {
                    {
                        setMessage("Hello, Your UserId is " + newUserData.userId);
                    }
                };
            }
        };
        UserResponse receivedResponse = userServiceImpl
                .helloUser()
                .invoke()
                .toCompletableFuture().get(5, SECONDS);
        System.out.println(receivedResponse);
        assertEquals("helloUser method fails ", "Hello, Your UserId is " + ID, receivedResponse.getMessage());
    }
}


Component Testing of UserServiceImplCompTest

But for writing the component testing, a fake server is started that makes calls to our services. Here, UserService and UserServiceImpl are treated as a single component, whereas ExternalService, which calls an external API, is another component. So, a stub is used in the case of ExternalService.

The code snippet is below:

public class UserServiceImplCompTest extends Mockito {
    private static final Integer ID = 1;
    private static final Integer USERID = 1;
    private static final String TITLE = "title";
    private static final String BODY = "body";
    private static UserData newUserData = new UserData() {
        {
            setId(ID);
            setUserId(USERID);
            setTitle(TITLE);
            setBody(BODY);
        }
    };
    private static UserService service;
    private static ServiceTest.TestServer server;
    private static ServiceTest.Setup setup = defaultSetup()
            .withCassandra(false)
            .withCluster(false)
            .withConfigureBuilder(b -> b.overrides
                    (bind(ExternalService.class).to(ExternalStub.class)));
    @BeforeClass
    public static void setup() {
        server = startServer(setup);
        service = server.client(UserService.class);
    }
    @AfterClass
    public static void tearDown() {
        if (server != null) {
            server.stop();
            server = null;
        }
    }
    @Test
    public void shouldGetUserData() throws Exception {
        UserResponse receivedResponse = service
                .helloUser()
                .invoke()
                .toCompletableFuture().get(100, SECONDS);
        assertEquals("helloUser method fails ", "Hello, Your UserId is " + ID, receivedResponse.getMessage());
    }
    static class ExternalStub implements ExternalService {
        @Override
        public ServiceCall<NotUsed, UserData> getUser() {
            return request -> CompletableFuture.completedFuture(newUserData);
        }
    }
}


The link to the above demo code is https://github.com/jasmine-k/Lagom-Unmanaged-Service-Demo.

References

This article was first published on the Knoldus blog.

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
java ,unit testing ,component testing ,lagom

Published at DZone with permission of Jasmine Kaur, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}