简体   繁体   中英

AssertJ testing on a collection: what is better: 'extracting' or Java8 forEach

I'm new to AssertJ and using it to unit-test my written code and was thinking how to assert a list.

Lets assume we have a list of Consumers Entities. each Entity has it own Phone, own ServiceProvider which has it own Name and EntityName.

Now we want to assert that each Entity from a repository gets the right data, so we want to test that each item on list has equal Phone.

ConsumerEntity savedConsumer1 = Consumer(phone, name, serviceProvider)
List<ConsumerEntity> consumerListFromRepository = repository.findAllByPhone(phone)

Now I want to test that the data given from Repository is correct,

I can use this:

   assertThat(consumerListFromRepository)
            .extracting(ConsumerEntity::getPhone())
            .containsOnly(savedConsumer1.getPhone());

Or I can do this with forEach (java 8):

   consumerListFromRepository.forEach(consumerEntity ->
   assertThat(consumerEntity.getPhone()).isEqualTo(savedConsumer1.getPhone()));

1. Which one is faster/simple-r/readable? I will go for the forEach for less lines of code but less read-ability as well.

2. Is there any other way to do it 1liner like the foreach but with asserThat? so it will be readable and simple - and without the need to use EqualTo each

time? something like:

   asserThat(list).forEach........

3. Which one is faster? Extracting or forEach?

Thanks!

I'm not sure that "faster" is a primary concern here. It's likely that any performance difference is immaterial; either the underlying implementations are ~equivalent in terms of non-functionals or - since the context here is a unit test - the consumerListFromRepository is trivially small thereby limiting the scope for any material performance differences.

I think your main concerns here should be

  • Making it as easy as possible for other developers to:
    • Understand/reason about your test case
    • Edit/refactor your test case
  • Ensuring that your approach to asserting is consistent with other test cases in your code base

Judging which of your two approaches best ticks this box is somewhat subjective but I think the following considerations are relevant:

  • The Java 8 forEach construct is well understood and the isEqualTo matcher is explicit and easily understood
  • The AssertJ extracting helper paired with the containsOnly is less common that Java8's forEach construct but this pairing reads logically and is easily understood

So, IMHO both approaches are valid. If your code base consistently uses AssertJ then I'd suggest using the extracting helper paired with the containsOnly matcher for consistency. Otherwise, use whichever of them reads best to you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM