Skip to content
javahacks.dev
Vaadin

Test Vaadin Views With Unit Tests and Browser Tests

Test Vaadin Flow views at two levels: fast unit tests that drive components without a browser, and end to end browser tests with TestBench or Playwright.

6 min read
Summarize in AI
Flat illustration of a browser page built from server-side components, with the Vaadin, HTML5, CSS and Thymeleaf logos.

A Vaadin view is a Java object. Its components, their values and their listeners all live on the server, which means most of what a view does can be checked without a browser. That changes the usual testing trade-off: you can cover forms, validation, navigation and grid contents at the speed of unit tests, and keep a few slow browser tests for what only a browser can show. This post sets out three levels, what belongs in each and how to shape views so they are testable. It uses Vaadin 25, Spring Boot 4 and JDK 25.

Level 0: test the logic without a UI

The cheapest test is for code that has no UI in it. If a view calculates a total, validates an address or decides which buttons to enable, move the decision into a plain class and test it with JUnit.

src/test/java/com/example/checkout/ShippingRulesTest.javajava
class ShippingRulesTest {

    @Test
    void free_shipping_from_fifty_pounds() {
        var rules = new ShippingRules();
        assertEquals(BigDecimal.ZERO, rules.cost(new BigDecimal("50.00"), "GB"));
        assertEquals(new BigDecimal("4.99"), rules.cost(new BigDecimal("49.99"), "GB"));
    }
}

This test needs no Spring context and runs in microseconds. The view calls rules.cost(...) and sets a label. The more the view is a thin shell over services, the more of the suite lives at this level. This is the same advice as in a practical testing strategy: put the behaviour where it is cheapest to check.

Level 1: server-side view tests

Some behaviour is in the view itself: which fields are required, what happens on a click, what the grid shows after a search. Because the component tree is Java, you can drive it directly. Vaadin provides a browserless testing library (check the Vaadin 25 testing page for the exact artifact name for your JUnit version) that creates a mock UI and session, navigates to a route and offers a query API for components.

java
@SpringBootTest
class ContactViewTest extends SpringBrowserlessTest {

    @MockitoBean ContactService contacts;

    @Test
    void shows_an_error_when_the_name_is_empty() {
        navigate(ContactView.class);

        $(Button.class).withText("Save").single().click();

        var name = $(TextField.class).withCaption("Name").single();
        assertTrue(name.isInvalid());
        assertEquals("Name is required", name.getErrorMessage());
        verifyNoInteractions(contacts);
    }

    @Test
    void saves_a_valid_contact() {
        navigate(ContactView.class);

        test($(TextField.class).withCaption("Name").single()).setValue("Ada");
        test($(Button.class).withText("Save").single()).click();

        verify(contacts).save(argThat(c -> c.name().equals("Ada")));
    }
}

The test base class sets up the Vaadin environment around a Spring context. $(Type.class) queries the component tree, withText and withCaption narrow the match, and test(component) returns a wrapper that simulates user interaction, respecting enabled and visible state: clicking a disabled button does nothing, as in a browser. A real click goes through listeners, binders and validators, so the test covers the form logic end to end except for the client.

Use @MockitoBean to replace services, as explained in replacing beans in Spring tests. Be aware that each different set of mocks creates a separate cached application context. Forms and validation behave as described in Binder validation, so the tests above also pin down the messages users see.

These tests run in tens of milliseconds each once the context is warm. Most view tests belong here: navigation, form validation, enabled and visible state, grid contents, dialogs and notifications.

Level 2: browser tests

A browserless test cannot see JavaScript errors, layout, a missing bundle, an unregistered web component or the effect of a content security policy. For those, drive a real browser against the running application. Vaadin's TestBench works with the same query API in a real browser, and Playwright for Java is a popular alternative:

java
@Test
void creates_a_contact_in_the_browser(Page page) {
    page.navigate("http://localhost:" + port + "/contacts");
    page.getByLabel("Name").fill("Ada");
    page.getByText("Save").click();
    assertThat(page.locator("vaadin-grid")).containsText("Ada");
}

Start the application on a random port with @SpringBootTest(webEnvironment = RANDOM_PORT), in production mode if you want to verify the bundle, which is the failure behind a blank page in production builds. Browser tests take seconds each, need a browser binary on the build machine and are flakier than the rest. Keep a small number: one smoke test per main flow, plus the cases that depend on the client. Retry once on CI, and record a trace on failure.

Grids, dialogs and notifications

A grid is testable through its data provider. The browserless API reads the rows the grid would show, after sorting and filtering, so you can assert that a search for "ada" leaves exactly one row without rendering anything. A dialog opened by a click appears in the UI's component tree, and you query it like any other component. A notification is added to the tree too, so you can assert on its text. These are the interactions that tempt people into browser tests, and none of them needs a browser.

Two traps are worth knowing. Code that uses UI.getCurrent() from a background thread returns null, as in production, so the test shows the same bug as the real application. And a test that depends on the order of a lazy grid's queries should stub the service to return a fixed page, because the data provider calls the service with offsets and limits and an unstable fake produces flaky results.

Keeping the suite fast

Share one application context across view tests by using the same mock set in a base class. Build the object graph once, and reset mocks between tests. A suite of two hundred browserless tests that reuses one context finishes in seconds; the same suite with a distinct set of mocks per class spends most of its time starting contexts. Count context starts in the logs and treat a rise as a regression.

What belongs where

CheckLevel
A business rule or calculation0, plain JUnit
Required fields, validation messages1, browserless
Button enabled after selecting a row1
Navigation and route parameters1
Grid shows the right rows for a filter1
The production bundle loads2
A custom web component renders2
Drag and drop, keyboard shortcuts, layout2

A rough ratio is many tests at level 0 and 1 for each one at level 2. If the suite has more browser tests than server-side ones, it will be slow and flaky and the feedback loop will suffer.

Make views testable

Give components stable handles. A TextField with a label is queryable by caption, and an id set with setId("contact-name") survives a rewording of the label. Avoid tests that rely on position in a layout or on CSS class names. Keep constructors light: inject services and build components, but leave data loading to onAttach or a method the test can call. Keep the view's dependencies as interfaces, so a test can pass a fake.

Where this approach is weaker

Browserless tests do not run the client side of custom components, so a component with its own JavaScript needs a level 2 test. They are also tied to the testing library's version: upgrade it with Vaadin. The official guidance is in the Vaadin testing documentation, and Playwright's Java API is documented at playwright.dev/java.

Also inTesting
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.