{{announcement.body}}
{{announcement.title}}

Unit Testing and Integration Testing in Practice

DZone 's Guide to

Unit Testing and Integration Testing in Practice

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

· DevOps Zone ·
Free Resource

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.

Topics:
automated testing ,java ,junit ,junit basics ,mockito ,software quality ,software test automation ,software testing ,unit testing ,vaadin

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}