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:
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:
// Iterate over the list elements
before aforeach
loop: Bad.But I want to remark this is rather a personal/organizational preference than an absolute truth.