Unit Testing and Integration Testing in Practice
In this article, take a look at unit testing and integration testing in practice.
Join the DZone community and get the full member experience.
Join For FreeAutomating 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:
xxxxxxxxxx
public class AgeService {
public int getAgeByBirthDate(LocalDate date) {
return Period.between(date, LocalDate.now()).getYears();
}
}
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:
xxxxxxxxxx
int age = new AgeService().calculateAge(
LocalDate.now().minusYears(31)
);
// 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:
x
import org.junit.Test;
import java.time.LocalDate;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class AgeServiceTest {
public void shouldReturnCorrectAge() {
AgeService ageService = new AgeService();
int expectedAge = 44;
LocalDate date = LocalDate.now().minusYears(expectedAge);
int actualAge = ageService.getAgeByBirthDate(date);
assertThat(actualAge, is(expectedAge));
}
}
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:
x
public class MainView extends Composite<VerticalLayout> {
private final AgeService ageService;
public MainView(AgeService ageService) {
this.ageService = ageService;
DatePicker datePicker = new DatePicker("Birth date");
Button button = new Button("Calculate age");
getContent().add(datePicker, button);
button.addClickListener(event -> calculateAge(datePicker.getValue()));
}
protected void calculateAge(LocalDate date) {
if (date == null) {
showError();
} else {
showAge(date);
}
}
protected void showError() {
Notification.show("Please enter a date.");
}
protected void showAge(LocalDate date) {
int age = ageService.getAgeByBirthDate(date);
String text = String.format("Age: %s years old", age);
getContent().add(new Paragraph(text));
}
}
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:
xxxxxxxxxx
import org.junit.Test;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.*;
public class MainViewTest {
public void shouldShowErrorOnNullDate() {
MainView mainView = mock(MainView.class);
doCallRealMethod().when(mainView).calculateAge(anyObject());
mainView.calculateAge(null);
verify(mainView).showError();
}
}
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:
xxxxxxxxxx
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:
x
public class MainViewIT extends AbstractViewTest {
public void shouldShowNotificationOnNullDate() {
DatePickerElement datePicker = $(DatePickerElement.class).first();
datePicker.clear();
ButtonElement button = $(ButtonElement.class).first();
button.click();
NotificationElement notification = $(NotificationElement.class).waitForFirst();
boolean isOpen = notification.isOpen();
assertThat(isOpen, is(true));
}
}
You can create a project at https://vaadin.com/start and run the integration tests as follows:
xxxxxxxxxx
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.
Opinions expressed by DZone contributors are their own.
Comments