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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • 7 Awesome Libraries for Java Unit and Integration Testing
  • Maven Plugin Testing - in a Modern Way - Part I
  • Mocking and Its Importance in Integration and E2E Testing
  • The Cost-Benefit Analysis of Unit, Integration, and E2E Testing

Trending

  • Next-Gen IoT Performance Depends on Advanced Power Management ICs
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • How to Write for DZone Publications: Trend Reports and Refcards
  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Unit Testing and Integration Testing in Practice

Unit Testing and Integration Testing in Practice

In this article, take a look at unit testing and integration testing in practice.

By 
Alejandro Duarte user avatar
Alejandro Duarte
DZone Core CORE ·
Apr. 22, 20 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
30.8K Views

Join the DZone community and get the full member experience.

Join For Free

Automating software testing is a practice that allows developers to avoid repetitive manual checks to verify if an application works correctly. These tests can be automated by implementing them using programming languages, frequently the same programming language used to develop the application to test.

Depending on the coverage of the tests, they can be classified as unit tests or integration tests. Unit tests target a single unit typically defined as a method. Integration tests target multiple parts of an application and frequently need external systems like databases or web services configured for testing purposes.

In this article, you'll learn about unit testing and integration testing of Java web applications developed with the Vaadin framework. You'll learn about the basic concepts and libraries such as JUnit, Mockito, and Vaadin Test Bench.

Implementing a Unit Test

Unit testing is an essential technique you can use to automate software testing. Let's say we have the following class:

Java
 




xxxxxxxxxx
1


 
1
public class AgeService {
2

          
3
    public int getAgeByBirthDate(LocalDate date) {
4
        return Period.between(date, LocalDate.now()).getYears();
5
    }
6
  
7
}



You might want to create a test to verify that this method calculates the correct age when you pass a valid date. For example, if you are using this method somewhere in your app, you could write something like the following:

Java
 




xxxxxxxxxx
1


 
1
int age = new AgeService().calculateAge(
2
    LocalDate.now().minusYears(31)
3
);
4
// age has to be 31 at this point



Of course, if you already know the age is 31 there's no point to call the method, but bear with me.

We can use a slightly modified version of the previous snippet of code in a test using a library called JUnit:

Java
 




x


 
1
import org.junit.Test;
2
import java.time.LocalDate;
3
import static org.hamcrest.CoreMatchers.is;
4
import static org.junit.Assert.assertThat;
5

          
6
public class AgeServiceTest {
7

          
8
    @Test
9
    public void shouldReturnCorrectAge() {
10
        AgeService ageService = new AgeService();
11
        int expectedAge = 44;
12
        LocalDate date = LocalDate.now().minusYears(expectedAge);
13

          
14
        int actualAge = ageService.getAgeByBirthDate(date);
15
        assertThat(actualAge, is(expectedAge));
16
    }
17

          
18
}



This class should be placed in the src/test/java/ directory in Maven projects that use the default configuration for directories. You can run the test with mvn test or using your IDE of choice.

Here's a video that shows how to implement and run this test in more detail:

Using Mocks and Stubs

Since unit testing deals with single portions of code (a unit), you will frequently need to use some sort of mechanism to avoid testing more code than you want. Mockito is one of the java frameworks for unit testing that allows you to isolate code.

Suppose you are coding a Vaadin view like the following:

Java
 




x


 
1
public class MainView extends Composite<VerticalLayout> {
2

          
3
    private final AgeService ageService;
4

          
5
    public MainView(AgeService ageService) {
6
        this.ageService = ageService;
7

          
8
        DatePicker datePicker = new DatePicker("Birth date");
9
        Button button = new Button("Calculate age");
10
        getContent().add(datePicker, button);
11

          
12
        button.addClickListener(event -> calculateAge(datePicker.getValue()));
13
    }
14

          
15
    protected void calculateAge(LocalDate date) {
16
        if (date == null) {
17
            showError();
18
        } else {
19
            showAge(date);
20
        }
21
    }
22

          
23
    protected void showError() {
24
        Notification.show("Please enter a date.");
25
    }
26

          
27
    protected void showAge(LocalDate date) {
28
        int age = ageService.getAgeByBirthDate(date);
29
        String text = String.format("Age: %s years old", age);
30
        getContent().add(new Paragraph(text));
31
    }
32

          
33
}



You want to make sure the  showError  method gets called when you pass a  null  date to the  calculateAge  method. In this scenario, the unit is the  calculateAge  method. You should only execute the lines of code that form that method and only that method. The problem is that  calculateAge  calls other methods and it could potentially even indirectly use other classes (like the  AgeService  class for instance).

Since you don't want to execute any lines of code outside the  calculateAge  method you can use Mockito to create a mock of the class, convert it to a stub, and verify whether the  showError  method is called when you pass a  null  date to  calculateAge . Here's how to do it:

Java
 




xxxxxxxxxx
1
17


 
1
import org.junit.Test;
2
import static org.mockito.Matchers.anyObject;
3
import static org.mockito.Mockito.*;
4

          
5
public class MainViewTest {
6

          
7
    @Test
8
    public void shouldShowErrorOnNullDate() {
9
        MainView mainView = mock(MainView.class);
10
        doCallRealMethod().when(mainView).calculateAge(anyObject());
11

          
12
        mainView.calculateAge(null);
13
        verify(mainView).showError();
14
    }
15

          
16
}



Notice how we configure the  mainView  instance to call the real  calculateAge  method but not the  showError  or any other method in the  MainView  class, including its constructor. You can try placing breakpoints in the  showError  and constructor to see that this is true.

Here's a video that shows how to implement this test from scratch:


Controlling the Browser to Implement Integration Tests

When you are developing web applications, you might want to be able to create a script that controls the browser and type and click on UI elements on the page. You can use a tool like Selenium or, in the case of Vaadin applications, Vaadin TestBench.

Tests implemented with Vaadin TestBench look similar to a unit test with JUnit, but when they run, the tool starts the whole application, opens a browser and controls it to follow the "instructions" in your test.

The tests themselves are formed by calls to methods to "select" UI components in the page in a similar way that you would do with JQuery. For example, to select a DatePicker that's visible on the page, you can write:

Java
 




xxxxxxxxxx
1


 
1
DatePickerElement datePicker = $(DatePickerElement.class).first();



Then you can, for example, set a date on it, or call any other method to configure what you want to test. Here's a complete integration test implemented with Vaadin TestBench:

Java
 




x


 
1
public class MainViewIT extends AbstractViewTest {
2

          
3
    @Test
4
    public void shouldShowNotificationOnNullDate() {
5
        DatePickerElement datePicker = $(DatePickerElement.class).first();
6
        datePicker.clear();
7
        ButtonElement button = $(ButtonElement.class).first();
8
        button.click();
9

          
10
        NotificationElement notification = $(NotificationElement.class).waitForFirst();
11
        boolean isOpen = notification.isOpen();
12
        assertThat(isOpen, is(true));
13
    }
14

          
15
}



You can create a project at https://vaadin.com/start and run the integration tests as follows:

Plain Text
 




xxxxxxxxxx
1


 
1
mvn verify -Pintegration-tests



Here's a video that shows how to implement the previous integration test from scratch:


You can find the complete source at https://github.com/alejandro-du/community-answers/tree/master/unit-testing.

unit test Integration Integration testing

Opinions expressed by DZone contributors are their own.

Related

  • 7 Awesome Libraries for Java Unit and Integration Testing
  • Maven Plugin Testing - in a Modern Way - Part I
  • Mocking and Its Importance in Integration and E2E Testing
  • The Cost-Benefit Analysis of Unit, Integration, and E2E Testing

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!