Assertj-core: Lambda-getter based version of hasFieldOrPropertyWithValue

Created on 4 Jun 2018  路  3Comments  路  Source: assertj/assertj-core

Summary

Can we add org.assertj.core.api.AbstractObjectAssert.hasPropertyWithValue(Function<T,V> getter, V expectedValue) ?

Example

class Car {
  private String name;
  public String getName() { return name; }
}

Assertions.assertThat(someCar).hasPropertyWithValue(Car::getName, "myCarName");

Most helpful comment

I'm fine with assertThat(new Car()).returns("myCarName", from(Car::getName));. I was looking for something that would allow me to chain few property assertions in compile safe manner (ie. without referring to field by its name as String). I was confused that this is not possible with hasPropertyWithValue - maybe it's worth suggesting returns as alternative in javadoc of hasPropertyWithValue?

All 3 comments

When testing only one property, it is imho more readable to write

assertThat(someCar.getName()).isEqualTo("myCarName");

For a small number of properties

assertThat(someCar).extracting(Car::getName, Car::getManufacturer).containsExactly("myCarName", "myCarManufacturer");

can be used.

There is also the more general

assertThat(new Car()).returns("myCarName", from(Car::getName));

were from is optional, so it which can be shortened to:

assertThat(new Car()).returns("myCarName", Car::getName);

Not saying that we should not add hasPropertyWithValue, just listing the existing options. 馃槂

I agree with @PascalSchumacher, moreover we will adding another extracting that takes only one lambda https://github.com/joel-costigliola/assertj-core/issues/1246 which will allow you to write:

```java
assertThat(someCar).extracting(Car::getName).isEqualTo("myCarName");
````

@rpost would that work for you ?

I'm fine with assertThat(new Car()).returns("myCarName", from(Car::getName));. I was looking for something that would allow me to chain few property assertions in compile safe manner (ie. without referring to field by its name as String). I was confused that this is not possible with hasPropertyWithValue - maybe it's worth suggesting returns as alternative in javadoc of hasPropertyWithValue?

Was this page helpful?
0 / 5 - 0 ratings