How to do UI Unit Testing using TestViews containing component under test?

Hi,

I’m trying to add some specific test for certain more complex components. These components extend VerticalLayout, and have some interaction between different sub-components.

I thought I would use UI Unit Testing for this.

The thing here is that the entry point is to navigate to a Route and then to interact with components on the page.

Since I want to test this component in isolation I decided to create a new Route, with just that component in the test module of the application.

@Route("test-my-component")
class MyComponentTestView extends VerticalLayout {

    public MyComponentTestView(SomeService someService) {
        add(new MyComponent(someService));
    }
}

And then my test would look like this:

@SpringBootTest(classes = MyTestConfiguration.class)
@ComponentScan(basePackages = "...")
class MyComponentTest extends SpringUIUnitTest {

    @MockBean
    private SomeService someService;

    @Test
    public void testMyComponent() {
        // mocking the service
        when(someService.loadData()).thenReturn(List.of(...));

        final MyComponentTestView navigate = navigate(MyComponentTestView.class);
        ... 

    }
}

When I run this, I see output from Vaadin listing all the discovered views, but my TestView, which is in the test-module (not main) is not being discovered. Is there a way to include this TestView? And preferably even exclude the Views not under test?

Or is my whole idea to do these kinds of tests not how it was intended?

Thank you!
Kristof

You can restrict route scan by adding the @ViewPackages annotation to the test class (Getting Started | UI Unit Testing | Testing | Flow | Vaadin Docs).

About the test view not being found, it could be because of the package protected visibilty of the view class.

4 Likes

Thank you Marco!

Your answer was spot on! Got it working now!

1 Like

Another approach to this is to separate implementation and tests of components used in the project in a separate module.

That is what I have done in this demo project. vaadin-create23/vaadincreate-components at master · TatuLund/vaadin-create23 · GitHub (It is Vaadin 8 project, but the same can be done with any Vaadin version)

Technically the setup of such module is identical to add-on project, like what I have here GitHub - TatuLund/TwinColSelect: TwinColSelect component for Vaadin 14, 23 and 24. And where I actually do have UI Unit Tests used to verify the component: TwinColSelect/src/test/java/org/vaadin/tatu/ViewTest.java at v24 · TatuLund/TwinColSelect · GitHub

The sub-module design allows to use layered testing with unit, ui unit and browser tests.

I wrote blog post about component testing a little while back: Custom component unit and integration testing tips | Vaadin

3 Likes

Thanks for the pointers!

I will definitely go through this!