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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
What's in store for DevOps in 2023? Hear from the experts in our "DZone 2023 Preview: DevOps Edition" on Fri, Jan 27!
Save your seat
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Unit Testing vs. Component Testing in Lagom

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.

Jasmine Kaur user avatar by
Jasmine Kaur
·
Nov. 09, 17 · Tutorial
Like (7)
Save
Tweet
Share
33.23K Views

Join the DZone community and get the full member experience.

Join For Free

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

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

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

This article was first published on the Knoldus blog.

unit test

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Explainer: Building High Performing Data Product Platform
  • Debugging Streams and Collections
  • Comparing Flutter vs. React Native
  • Simulating and Troubleshooting StackOverflowError in Kotlin

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: