Unit Testing vs. Component Testing in Lagom

Table of contents
Reading Time: 4 minutes

Let’s first understand the basic difference between unit testing and component testing and then we will have a look at a practical application of unmanaged service in lagom with its test cases.

Difference between Unit Testing and Component Testing

Unit Testing involves testing of individual units(classes) to demonstrate that the program executes as per the specification and 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 for 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 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 fake server should be started which will make calls to our services and produce the result so that we could assert it against the expected result.

Practical Application

Let’s look at a demo application i.e. an unmanaged-service in lagom which 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 :

i) ExternalService– This is an unmanaged service which 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 consist of an interface :

i) UserService – It consists of a ServiceCall named as 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 manipulate the data and returns an object of class UserResponse having the a single filed i.e. message.

The code snippet for the UserModule is given below:

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 :

i) UserServiceImpl

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

ii) 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 for testing my application.

i) Unit Testing Of UserServiceImpl

In order to write the Unit test cases for UserSeviceImpl, an instance of the class is created and marked with annotation @Tested. This instance should be used to call the method which has to be tested. All the methods of other classes and modules are mocked using Expectation. The code snippet for the same is given 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 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());
    }
}

ii) Component Testing of UserServiceImplCompTest

But for writing the Component testing, a fake server is started which 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, stub is used in case of ExternalService.

The code snippet for the same is given 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 for the above demo code is :

https://github.com/knoldus/lagom-unit-and-component-testing

References :

https://www.lagomframework.com/documentation/1.3.x/java/Home.html

http://jmockit.org/tutorial/Introduction.html


knoldus-advt-sticker


3 thoughts on “Unit Testing vs. Component Testing in Lagom5 min read

  1. Very helpful to get started, thanks. Could you explain why in the last test method ‘shouldGetUserData()’, you use 100 seconds and the message “helloUser method fails” in your assertEquals? Aren’t you testing that the method is ok?

Comments are closed.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading