'JUnit testing Vaadin 23 elements using localization

I wan't to JUnit test my layout which uses Vaadin localization but I face an error:

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);}
}

My JUnit test:

  @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());
  }

I get this error when running the test:

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

If I don't use "getTransaltion" my test is running and green.



Solution 1:[1]

Working solution:

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());
  }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Istvan Csenkey-Sinko