Skip to content

make asList() type safe #3105

@Illutax

Description

@Illutax

Feature summary

The method asList() should return a correctly typed list.

Example

Assume a type Bar with the filed strings: List<String>. And a type Foo with the field bar: List<Bar> (both with default getter and all-args-constructor).

class Foo {
  private final List<Bar> bars;
}

class Bar {
  private final List<String> strings;
}

The following block is type-safe

import static java.util.Arrays.asList;

Bar bar = new Bar(asList("a","b"));
assertThat(bar)
  .extracting(Bar::getStrings)
  .asList()
  .containsExactly("a", "b");

When working with nested structures and using Assert.asList() the returned list will be of type Object.

Foo myComplexFoo = new Foo(asList(new Bar(asList("a", "b")), new Bar(asList("a", "b"))));
assertThat(myComplexFoo)
  .extracting(Foo::getBars)
  .asList()
  .extracting(o -> ((Bar)o).getStrings())
  .containsExactly(asList("a", "b"), asList("a", "b"));

We had to cast the Object back to a Bar for working further with it.

The proposal creates an overload to the asList() which gets a type such that we can further assert the structure like:

Foo myComplexFoo = new Foo(asList(new Bar(asList("a", "b")), new Bar(asList("a", "b"))));
assertThat(myComplexFoo)
  .extracting(Foo::getBars)
  .asTypedList(Bar.class)
  .extracting(Bar::getStrings)
  .containsExactly(asList("a", "b"), asList("a", "b"));

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: declinedA suggestion or change that we don't feel we should currently apply

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions