Home > Software design >  Do we need to test findAll methods in Unit Tests?
Do we need to test findAll methods in Unit Tests?

Time:09-23

I have the following service method:

public List<LabelDTO> findAllByLanguage(Language language) {
    final Map<Pair<UUID, String>, List<TextLabelTranslatable>> valueList = 
        translatableRepository.findAllTranslatable();
    
    // code omitted 

    return labelDTOList;
}

I am trying to create the following Unit Test for this method:

@Test
public void demo_test() {

    List<LabelWithTranslatable> labelWithTranslatableList = new ArrayList<>();

    LabelWithTranslatable labelWithTranslatable1 = mock(LabelWithTranslatable.class);
    labelWithTranslatable1.getEntity().setId(123L);
    labelWithTranslatableList.add(labelWithTranslatable1);

    LabelWithTranslatable labelWithTranslatable2 = mock(LabelWithTranslatable.class);
    labelWithTranslatable2.getEntity().setId(456L);
    labelWithTranslatableList.add(labelWithTranslatable2);

    // translatableRepository.findAllTranslatable() returns "List<LabelWithTranslatable>"
    when(translatableRepository.findAllTranslatable())
        .thenReturn(labelWithTranslatableList);

    List<LabelDTO> result = labelService.findAllByLanguage(SupportedLanguage.en);


    // assertions
}

My questions are:

1. Do we need to test findAll() methods in Unit Tests? If so, should we create multiple records to the list and then compare the returned result by the expected filtered values?

2. I mock LabelWithTranslatable, but it has an entity and its value is null (labelWithTranslatable1.getEntity()). So, how should I mock that entity? Here is the relation:

LabelWithTranslatable:

public interface LabelWithTranslatable extends 
                     GenericTranslatable<Label, LabelTranslatable> {
}

GenericTranslatable:

public interface GenericTranslatable<E extends BaseEntity, T extends BaseTranslatableEntity> {
    E getEntity();

    T getTranslatable();
}

CodePudding user response:

Yes, you do need to test your findAllXxx methods -- the code represented by the //code omitted comment in your question needs test coverage.

As you suggest, you can do this by mocking the underlying repository.

To mock your LabelWithTranslatable instances you'll need to do:

LabelWithTranslatable labelWithTranslatable1 = mock(LabelWithTranslatable.class);
Label label1 = mock(Label.class);
when(label1.getId()).thenReturn(123L);
when(labelWithTranslatable1.getEntity()).thenReturn(label1);
labelWithTranslatableList.add(labelWithTranslatable1);
  • Related