Интеграционные тесты UI
Jmix позволяет писать тесты для слоя пользовательского интерфейса. В этих тестах вы можете открывать экраны, загружать данные, проверять содержимое компонентов UI, вносить изменения и моделировать действия пользователя, такие как нажатия кнопок.
| Используйте действие New → Advanced → UI Integration Test в окне инструментов Jmix, чтобы быстро создать интеграционный тест UI с помощью Studio. | 
Тесты пользовательского интерфейса Jmix запускают полный контекст Spring и могут взаимодействовать с базой данных, подобно интеграционным тестам бизнес-логики. Они близки к end-to-end тестам, основанным на управлении браузером с помощью Selenium WebDriver, в том что они могут проверять широкий спектр функциональности приложения, но в то же время их легко настроить, и выполняются они намного быстрее.
В каждом новом проекте Jmix включен пример интеграционного теста UI: класс UserUiTest, который проверяет экраны управления пользователями. Давайте рассмотрим конфигурацию и логику тестов пользовательского интерфейса, используя этот пример.
Для выполнения тестов UI проект должен содержать зависимость от модуля jmix-flowui-test-assist:
testImplementation 'io.jmix.flowui:jmix-flowui-test-assist'Класс теста приведен ниже.
package com.company.demo.user;
import com.company.demo.DemoApplication;
import com.company.demo.entity.User;
import com.company.demo.view.user.UserDetailView;
import com.company.demo.view.user.UserListView;
import io.jmix.core.DataManager;
import io.jmix.flowui.ViewNavigators;
import io.jmix.flowui.component.UiComponentUtils;
import io.jmix.flowui.component.grid.DataGrid;
import io.jmix.flowui.component.textfield.JmixPasswordField;
import io.jmix.flowui.component.textfield.TypedTextField;
import io.jmix.flowui.data.grid.DataGridItems;
import io.jmix.flowui.kit.component.button.JmixButton;
import io.jmix.flowui.testassist.FlowuiTestAssistConfiguration;
import io.jmix.flowui.testassist.UiTest;
import io.jmix.flowui.testassist.UiTestUtils;
import io.jmix.flowui.view.View;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
 * Sample UI integration test for the User entity.
 */
@UiTest (1)
@SpringBootTest(classes = {DemoApplication.class, FlowuiTestAssistConfiguration.class}) (2)
public class UserUiTest {
    @Autowired
    DataManager dataManager; (3)
    @Autowired
    ViewNavigators viewNavigators;
    @Test (4)
    void test_createUser() {
        // Navigate to user list view
        viewNavigators.view(UiTestUtils.getCurrentView(), UserListView.class).navigate();
        UserListView userListView = UiTestUtils.getCurrentView(); (5)
        // click "Create" button
        JmixButton createBtn = findComponent(userListView, "createBtn"); (6)
        createBtn.click();
        // Get detail view
        UserDetailView userDetailView = UiTestUtils.getCurrentView();
        // Set username and password in the fields
        TypedTextField<String> usernameField = findComponent(userDetailView, "usernameField");
        String username = "test-user-" + System.currentTimeMillis();
        usernameField.setValue(username);
        JmixPasswordField passwordField = findComponent(userDetailView, "passwordField");
        passwordField.setValue("test-passwd");
        JmixPasswordField confirmPasswordField = findComponent(userDetailView, "confirmPasswordField");
        confirmPasswordField.setValue("test-passwd");
        // Click "OK"
        JmixButton commitAndCloseBtn = findComponent(userDetailView, "saveAndCloseBtn");
        commitAndCloseBtn.click();
        // Get navigated user list view
        userListView = UiTestUtils.getCurrentView();
        // Check the created user is shown in the table
        DataGrid<User> usersDataGrid = findComponent(userListView, "usersDataGrid");
        DataGridItems<User> usersDataGridItems = usersDataGrid.getItems();
        Assertions.assertNotNull(usersDataGridItems);
        usersDataGridItems.getItems().stream()
                .filter(u -> u.getUsername().equals(username))
                .findFirst()
                .orElseThrow();
    }
    @AfterEach (7)
    void tearDown() {
        dataManager.load(User.class)
                .query("e.username like ?1", "test-user-%")
                .list()
                .forEach(u -> dataManager.remove(u));
    }
    @SuppressWarnings("unchecked")
    private static <T> T findComponent(View<?> view, String componentId) {
        return (T) UiComponentUtils.getComponent(view, componentId);
    }
}| 1 | Аннотация @UiTestопределяет расширение JUnit для запуска Vaadin, настройки экранов приложения и установки аутентификации. | 
| 2 | Аннотация @SpringBootTestдолжна объявить конфигурации приложения и модуляjmix-flowui-test-assist. | 
| 3 | Вы можете внедрять любые бины Spring, используя аннотацию @Autowired. | 
| 4 | Метод тест-кейса. | 
| 5 | Метод UiTestUtils.getCurrentView()возвращает экран, в настоящее время открытый через навигацию. | 
| 6 | Метод findComponent()возвращает компонент UI по его идентификатору. | 
| 7 | Метод, выполняемый после каждого тест-кейса, может использоваться для очистки тестовых данных. |