首页 > 解决方案 > Vaadin 10+,如何在 kaributesting 中触发 UI.getCurrent().access

问题描述

我想用 karibu-testing 测试 Vaadin 流组件。在这个组件中,我UI.getCurrent().access {}用来更新这个组件,但是在运行测试时,里面的代码access不会被执行。当我尝试UI.getCurrent().access {}在测试本身中使用时,结果相同......一些想法?

pom.xml

<dependency>
   <groupId>com.github.mvysny.kaributesting</groupId>
   <artifactId>karibu-testing-v10</artifactId>
   <version>1.1.4</version>
</dependency>

测试(科特林)

class MyUITest {

    @BeforeAll
    fun init() {
        MockVaadin.setup()
    }

    @BeforeEach
    fun setup() {
        UI.getCurrent().removeAll()
    }

    @Test
    fun testSometing() {
        UI.getCurrent().access {
            print("foo") // this line is not reachable
        }
    }
}

标签: kotlinvaadinvaadin-flowvaadin10

解决方案


我希望我没有误解你的问题。我试图用一个组件创建一个最小的示例,该组件UI.getCurrent().access {}用于更改 UI 中的某些内容。

在这里,我有一个组件,其中包含一个 TextField,其值为“hallo”。该组件中有一个方法可以将 TextField 的值更改为“嘿”。

该组件看起来像

package com.example.test;

import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.server.Command;

@Tag(value = "myComponent")
public class MyComponent extends Component {
    private TextField textField = new TextField();

    public MyComponent() {
        textField.setValue("hallo");
    }

    public void changeValueToHey() {
        UI.getCurrent().access((Command) () -> {
            textField.setValue("hey");
        });
    }

    public String getTextFieldValue() {
        return textField.getValue();
    }
}

然后我创建了一个 karibu 测试(v. 1.1.6),例如:

@Test
public void test() {
    MyComponent myComponent = new MyComponent();
    UI.getCurrent().add(myComponent);
    assertEquals("hallo", myComponent.getTextFieldValue());
    MockVaadin.INSTANCE.runUIQueue(true);
    myComponent.changeValueToHey();
    MockVaadin.INSTANCE.runUIQueue(true);
    assertEquals("hey", myComponent.getTextFieldValue());
}

runUIQueue在文档(https://github.com/mvysny/karibu-testing/tree/master/karibu-testing-v10)中找到了那些说:

问题是,Karibu Testing 在保持 UI 锁定的情况下运行测试。这大大简化了测试,但也阻止了另一个线程的异步更新,仅仅是因为测试持有锁!

解决方案是暂时释放测试线程中的 UI 锁,允许处理从后台线程发布的 UI.access() 任务。然后测试线程将重新获得锁并继续测试。


推荐阅读