2

I am trying to have proper assertion (with implicit null checks) for a property of a list element.

  • The first assertion is working as expected, except that it will generate no proper error message if actual is null.
  • The second is supposed to provide proper null check for actual, but it's not compiling.

Is there an option tweak the second assertion to make it work?

import java.util.List;

import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;

class ExampleTest {

    private static class Sub {

        private String value;

        public String getValue() {
            return value;
        }
    }

    private static class Example {

        private List<Sub> subs;

        public List<Sub> getSubs() {
            return subs;
        }
    }

    @Test
    void test() {
        Example actual = null;

        assertThat(actual.getSubs())//not null safe
                .extracting(Sub::getValue)
                .contains("something");

//        assertThat(actual)
//                .extracting(Example::getSubs)
//                .extracting(Sub::getValue)//not compiling
//                .contains("something");
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
André
  • 308
  • 2
  • 17

1 Answers1

4

For type-specific assertions, extracting(Function, InstanceOfAssertFactory) should be used:

assertThat(actual)
    .extracting(Example::getSubs, as(list(Sub.class)))
    .extracting(Sub::getValue) // compiles
    .contains("something");
Stefano Cordio
  • 1,687
  • 10
  • 20