google / google/truth

Allow custom assertions on the value of an Optional

Open
#315 4 comments 0 reactions 0 assignees View on GitHub
P3 type=addition
Dominant language
Java
Stars
2.8k
Forks
275
Avg merge
7m
Merged PRs (30d)
4

Description

When doing assertions on an Optional containing a simple type like a string, the current OptionalSubject#hasValue method is sufficient. However, when the Optional contains a custom type which might even have nested inner types, doing a simple equality check isn't always the desired way. Users will typically end up with code like this:
```
assertThat(person).isPresent();
Address address = person.getAddress();
assertThat(address.getStreet()).startsWith("D");
```

I suggest to add an additional assertThat() method to OptionalSubject which takes a function as second argument. This function maps the value of the Optional to an appropriate Subject. To make it properly work, OptionalSubject needs to be generified (which shouldn't break existing code). As result, the previous assertion could be written like:
```
assertThat(person, PersonSubject::assertThat).value().address().street().startsWith("D");
```

Or with a bit more verbose naming:
```
assertThat(person, PersonSubject::assertThat).hasValueThat().hasAddressThat().hasStreetThat().startsWith("D");
```

I intend to provide a pull request for this soon.

Does anybody have an opinion about the name of the method which allows to access the value (e.g. "value" or "hasValueThat"?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.