Unit Testing – Should //given //when and //then Comments Be Included?

commentsunit testing

I've joined a new team of great colleagues and a difference of opinion has come up concerning including //given //when and //then comment blocks in unit tests.

For example

public void mapToitemList_MapsCarsToitemsCorrectly_ForSingleFurrari() {
    // given
    String commercialProductName = "Furrari";
    String productNumber = "12423";
    BigDecimal numberOfScrews = BigDecimal.TEN;
    ValveType valveType = ValveType.GOOD;

    Car car = new Car() //
                    .withCommercialProductName(commercialProductName) //
                    .withProductCarNumber(productNumber) //
                    .withNumberOfScrewsAmount(new NumberOfScrewsAmount().withValue(numberOfScrews)) //
                    .withBalances(new Engine().withValves(new ValveType().withValue(valveType)));
    List<Car> carList = Collections.singletonList(car);

    // when
    List<Item> mappedListOfCars = CarMapper.mapToItemList(carList);

    // then 
    assertThat(mappedListOfCars).isNotEmpty();
    Item carAsItem = mappedListOfCars.get(0);

    assertThat(carAsItem.getCommercialProductName()).isEqualTo(commercialProductName);
    assertThat(carAsItem.getNumberOfSetsOfScrews().getValue()).isEqualTo(Convertor.numbersOfScrewsToNumberOfSets(numberOfScrews).getValue());

}

Currently my main reason to include them is because I'm used to it and the main counter-argument I'm getting is that comments should be shunned.

Does the added structure of these comments merit the use of comments? Martin Fowler mentions some people use them, but passes no judgment on it.

Best Answer

Code comments are usually taken as a bad practice because:

  • They add new artifacts to maintain in the future.
  • The code should be as simple and well written to be self-explanatory.

That said, as usual, there are no absolute truths. Personally, this kind of comments is positive to me as they add additional semantics to the code and let me know which section of the test I'm working on. Besides, it also enforces following a certain test coding structure.

So, to sum up:

  • Code comments that add no semantic to the code like // Iterate over the list elements before a foreach loop: Bad.
  • Code comments that add good semantic and enforces good practices: Good.

But I want to remark this is rather a personal/organizational preference than an absolute truth.