Testing Vaadin With Unit and Integration Tests

It is a common best practice to test as little code as possible in a single test. In this way, when things go wrong, only relevant tests fail. For UI testing, there are three main approaches:

  • Unit tests: for simple UI logic.

  • Integration tests: for more advanced UI logic.

  • End-to-end tests: to test what the user sees.

You can run unit and integration tests standalone, that is, without any external dependencies, such as a running server or database.

End-to-end tests require the application to be deployed and are run in a browser window to simulate an actual user.

In this chapter, you write and run unit and integration tests. The tutorial covers end-to-end tests in the next chapter.

Creating and Running Unit Tests for Simple UI Logic

The most minimal way of testing is to create a plain Java unit test. This only works with UI classes with no dependencies, no auto-wiring etc. For the ContactForm, you can create a unit test to verify that the form fields are correctly populated, based on the given bean.

Note
Put tests in the correct folder

All test classes should go in the test folder, src/test/java. Pay special attention to the package names. Use package-access for class fields. If the test isn’t in the same package as the class that’s being tested, you will get errors.

Create a new folder, src/test/java. In IntelliJ, right-click on the folder and select Mark Directory as > Test Sources Root. In the new folder, create a new package, com.example.application.views.list, and add a new ContactFormTest.java file with the code below.

ContactFormTest.java

  1. package com.example.application.views.list;
  2. import com.example.application.data.entity.Company;
  3. import com.example.application.data.entity.Contact;
  4. import com.example.application.data.entity.Status;
  5. import org.junit.Assert;
  6. import org.junit.Before;
  7. import org.junit.Test;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. import java.util.concurrent.atomic.AtomicReference;
  11. public class ContactFormTest {
  12. private List<Company> companies;
  13. private List<Status> statuses;
  14. private Contact marcUsher;
  15. private Company company1;
  16. private Company company2;
  17. private Status status1;
  18. private Status status2;
  19. @Before 1
  20. public void setupData() {
  21. companies = new ArrayList<>();
  22. company1 = new Company();
  23. company1.setName("Vaadin Ltd");
  24. company2 = new Company();
  25. company2.setName("IT Mill");
  26. companies.add(company1);
  27. companies.add(company2);
  28. statuses = new ArrayList<>();
  29. status1 = new Status();
  30. status1.setName("Status 1");
  31. status2 = new Status();
  32. status2.setName("Status 2");
  33. statuses.add(status1);
  34. statuses.add(status2);
  35. marcUsher = new Contact();
  36. marcUsher.setFirstName("Marc");
  37. marcUsher.setLastName("Usher");
  38. marcUsher.setEmail("marc@usher.com");
  39. marcUsher.setStatus(status1);
  40. marcUsher.setCompany(company2);
  41. }
  42. }
  1. The @Before annotation adds dummy data that is used for testing. This method is executed before each @Test method.

Now, add a test method that uses ContactForm:

ContactFormTest.java

  1. @Test
  2. public void formFieldsPopulated() {
  3. ContactForm form = new ContactForm(companies, statuses);
  4. form.setContact(marcUsher); 1
  5. Assert.assertEquals("Marc", form.firstName.getValue());
  6. Assert.assertEquals("Usher", form.lastName.getValue());
  7. Assert.assertEquals("marc@usher.com", form.email.getValue());
  8. Assert.assertEquals(company2, form.company.getValue());
  9. Assert.assertEquals(status1, form.status.getValue()); 2
  10. }
  1. Validates that the fields are populated correctly, by first initializing the contact form with some companies, and then setting a contact bean for the form.

  2. Uses standard JUnit assertEquals() methods to compare the values from the fields available through the ContactForm instance:

Similarly, test the save functionality of ContactForm.

ContactFormTest.java

  1. @Test
  2. public void saveEventHasCorrectValues() {
  3. ContactForm form = new ContactForm(companies, statuses);
  4. Contact contact = new Contact();
  5. form.setContact(contact); 1
  6. form.firstName.setValue("John"); 2
  7. form.lastName.setValue("Doe");
  8. form.company.setValue(company1);
  9. form.email.setValue("john@doe.com");
  10. form.status.setValue(status2);
  11. AtomicReference<Contact> savedContactRef = new AtomicReference<>(null);
  12. form.addListener(ContactForm.SaveEvent.class, e -> {
  13. savedContactRef.set(e.getContact()); 3
  14. });
  15. form.save.click(); 4
  16. Contact savedContact = savedContactRef.get();
  17. Assert.assertEquals("John", savedContact.getFirstName()); 5
  18. Assert.assertEquals("Doe", savedContact.getLastName());
  19. Assert.assertEquals("john@doe.com", savedContact.getEmail());
  20. Assert.assertEquals(company1, savedContact.getCompany());
  21. Assert.assertEquals(status2, savedContact.getStatus());
  22. }
  1. Initialize the form with an empty Contact.

  2. Populate values into the form.

  3. Capture the saved contact into an AtomicReference.

  4. Click the save button and read the saved contact.

  5. Once the event data is available, verify that the bean contains the expected values.

To run the unit test, right-click ContactFormTest and select Run ‘ContactFormTest’.

run unit test

When the test finishes, you will see the results at the bottom of the IDE window in the test-runner panel. As you can see, both tests passed.

tests passed

Creating and Running Integration Tests for More Advanced UI Logic

To test a class that uses @Autowire, a database, or any other feature provided by Spring Boot, you can no longer use plain JUnit tests. Instead, you can use the Spring Boot test runner. This does add a little overhead, but it makes more features available to your test.

To set up a unit test for ListView, create a new file, ListViewTest, in the com.example.application.views.list package:

ListViewTest.java

  1. package com.example.application.views.list;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringRunner;
  7. @RunWith(SpringRunner.class) 1
  8. @SpringBootTest
  9. public class ListViewTest {
  10. @Autowired
  11. private ListView listView;
  12. @Test
  13. public void formShownWhenContactSelected() {
  14. }
  15. }
  1. The @RunWith(SpringRunner.class) and @SpringBootTest annotations make sure that the Spring Boot application is initialized before the tests are run and allow you to use @Autowire in the test.

In the ListView class:

  1. Add the Spring @Component annotation to make it possible to @Autowire it.

  2. Also add @Scope("prototype") to ensure that every test run gets a fresh instance.

Side note: you didn’t need to add the annotation for normal application usage, as all @Route classes are automatically instantiated by Vaadin in a Spring-compatible way.

**ListView.java**

  1. @Component
  2. @Scope("prototype")
  3. @Route(value = "", layout = MainLayout.class)
  4. @PageTitle("Contacts | Vaadin CRM")
  5. public class ListView extends VerticalLayout {
  6. Grid<Contact> grid = new Grid<>(Contact.class);
  7. TextField filterText = new TextField();
  8. ContactForm form;
  9. CrmService service;
  10. // rest omitted
  11. }

Right-click the package that contains both tests, and select Run tests in ‘com.example.application.views.list’. You should see that both test classes run and result in three successful tests.

run package tests

three successful tests

Note
Integration tests take longer to run

You probably noticed that running the tests the second time took much longer. This is the price of being able to use @Autowire and other Spring features and can cost many seconds of startup time.

You can improve the startup time by explicitly listing the needed dependencies in the @SpringBootTest annotation using classes={…​}, mock parts of the application, or using other advanced techniques which are out of scope for this tutorial. Pivotal’s Spring Boot Testing Best Practices has tips to speed up your tests.

You can now add the actual test implementation, which selects the first row in the grid and validates that this shows the form with the selected Contact:

ListViewTest.java

  1. @Test
  2. public void formShownWhenContactSelected() {
  3. Grid<Contact> grid = listView.grid;
  4. Contact firstContact = getFirstItem(grid);
  5. ContactForm form = listView.form;
  6. Assert.assertFalse(form.isVisible());
  7. grid.asSingleSelect().setValue(firstContact);
  8. Assert.assertTrue(form.isVisible());
  9. Assert.assertEquals(firstContact.getFirstName(), form.firstName.getValue());
  10. }
  11. private Contact getFirstItem(Grid<Contact> grid) {
  12. return( (ListDataProvider<Contact>) grid.getDataProvider()).getItems().iterator().next();
  13. }

The test verifies that the form logic works by:

  • asserting that the form is initially hidden,

  • selecting the first item in the grid and verifying that:

    • the form is visible,

    • the form is bound to the correct Contact by ensuring the right name is visible in the field.

Rerun the tests. They should all pass.

You now know how to test the application logic both in isolation with unit tests and by injecting dependencies to test the integration between several components. In the next chapter, the tutorial covers how to test the entire application in the browser.

migration assistance

Download free e-book.
The complete guide is also available in an easy-to-follow PDF format.

https://pages.vaadin.com/en/build-a-modern-web-app-with-spring-boot-vaadin-pdf

Open in anew tab

Show code

render-banner.ts

  1. export class RenderBanner extends HTMLElement {
  2. connectedCallback() {
  3. this.renderBanner();
  4. }
  5. renderBanner() {
  6. let bannerWrapper = document.getElementById('tocBanner');
  7. if (bannerWrapper) {
  8. return;
  9. }
  10. let tocEl = document.getElementById('toc');
  11. // Add an empty ToC div in case page doesn't have one.
  12. if (!tocEl) {
  13. const pageTitle = document.querySelector(
  14. 'main > article > header[class^=PageHeader-module--pageHeader]'
  15. );
  16. tocEl = document.createElement('div');
  17. tocEl.classList.add('toc');
  18. pageTitle?.insertAdjacentElement('afterend', tocEl);
  19. }
  20. // Prepare banner container
  21. bannerWrapper = document.createElement('div');
  22. bannerWrapper.id = 'tocBanner';
  23. tocEl?.appendChild(bannerWrapper);
  24. // Banner elements
  25. const text = document.querySelector('.toc-banner-source-text')?.innerHTML;
  26. const link = document.querySelector('.toc-banner-source-link')?.textContent;
  27. const bannerHtml = `<div class='toc-banner'>
  28. <a href='${link}'>
  29. <div class="toc-banner--img"></div>
  30. <div class='toc-banner--content'>${text}</div>
  31. </a>
  32. </div>`;
  33. bannerWrapper.innerHTML = bannerHtml;
  34. // Add banner image
  35. const imgSource = document.querySelector('.toc-banner-source .image');
  36. const imgTarget = bannerWrapper.querySelector('.toc-banner--img');
  37. if (imgSource && imgTarget) {
  38. imgTarget.appendChild(imgSource);
  39. }
  40. }
  41. }