Issue
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
Class under test CallSearchFilters2 contains a TextField, which you add to a layout. This wont work in unit test without mocking several Vaadin classes, which are needed to be in place in order to e.g. layout.add(..) to work. VaadinService, VaadinSession and UI are some of those, but actually some other classes are needed. As this is tedious to do from the scratch, I would recommend to check if you would like to use Karibu library (which is essentially about providing this mocks to you).
https://github.com/mvysny/karibu-testing
Answered By - Tatu Lund
Answer Checked By - Cary Denson (JavaFixing Admin)