JUnit使用本地化测试Vaadin 23元素



我不想JUnit测试我的使用Vaadin本地化的布局,但我面临一个错误:

public class CallSearchFilters2 extends HorizontalLayout {
private Binder<SearchQueryFormDTO> binder = new Binder<>(SearchQueryFormDTO.class);
protected TextField participantName;
public CallSearchFilters2() {
participantName = new TextField(getTranslation("quickSearch.name"));
// participantName = new TextField("Name");
participantName.setClearButtonVisible(true);
participantName.setHelperText("For partial search use %");
binder.forField(participantName).bind(SearchQueryFormDTO::getName, SearchQueryFormDTO::setName);
add(participantName);
binder.addValueChangeListener(valueChangeEvent -> fireEvent(new FilterChangedEvent(this, false)));
}...
public void loadFromDTO(SearchQueryFormDTO dto) {binder.readBean(dto);}
}

我的JUnit测试:

@Test
public void loadFromSearchQuery() {
final String name = "NAME";
SearchQueryFormDTO dto = new SearchQueryFormDTO();
dto.setName(name);
CallSearchFilters2 callSearchFilters = new CallSearchFilters2();
callSearchFilters.loadFromDTO(dto);
Assert.assertEquals(name, callSearchFilters.participantName.getValue());
}

运行测试时出现以下错误:

java.lang.NullPointerException: Cannot invoke "com.vaadin.flow.server.VaadinService.getInstantiator()" because the return value of "com.vaadin.flow.server.VaadinService.getCurrent()" is null

如果我不使用">getTransaltion";我的测试正在运行,而且是绿色的。

测试中的类CallSearchFilters2包含一个TextField,您可以将其添加到布局中。如果不嘲笑几个Vaadin类,这在单元测试中就无法工作,这些类需要就位才能工作,例如layout.add(..(。VaadiService、VaadinSession和UI就是其中的一些,但实际上还需要一些其他类。由于从头开始做这件事很乏味,我建议您检查一下是否要使用Karibu库(本质上是为了向您提供这些mock(。

https://github.com/mvysny/karibu-testing

工作解决方案:

package com.tcandc.carin.webui.next.views.callsearch;
import com.github.mvysny.kaributesting.v10.MockVaadin;
import com.github.mvysny.kaributesting.v10.Routes;
import com.vaadin.flow.component.UI;
import kotlin.jvm.functions.Function0;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class CallSearchFiltersTest2 {
private static Routes routes;
@BeforeAll
public static void createRoutes() {
routes = new Routes().autoDiscoverViews("com.tcandc.carin.webui.next");
}
@BeforeEach
public void setupVaadin() {
final Function0<UI> uiFactory = UI::new;
MockVaadin.setup(routes, uiFactory);
}
@Test
public void loadFromSearchQuery() {
final String name = "NAME";
SearchQueryFormDTO dto = new SearchQueryFormDTO();
dto.setName(name);
CallSearchFilters2 callSearchFilters = new CallSearchFilters2();
callSearchFilters.loadFromDTO(dto);
Assert.assertEquals(name, callSearchFilters.participantName.getValue());
}
}

最新更新