Search code examples
javafluentassertj

AssertJ - continue with fluent assertions after checking class


Say I have a Map<String, Action> and I go like this:

    assertThat( spyActionMap.get( "a" ) ).isInstanceOf( Action.class );

... passes. Now I want to check that the Action obtained is the right one:

    assertThat( spyActionMap.get( "a" ) ).isInstanceOf( Action.class ).getValue( Action.NAME ).isEqualTo( "Go crazy" );

... doesn't compile, not surprisingly. Is there any way to do this kind of thing?


Solution

  • You can try isInstanceOfSatisfying and specify your assertions in a Consumer:

    Object yoda = new Jedi("Yoda", "Green");
    Object luke = new Jedi("Luke Skywalker", "Green");
    
    Consumer<Jedi> jediRequirements = jedi -> {
       assertThat(jedi.getLightSaberColor()).isEqualTo("Green");
       assertThat(jedi.getName()).doesNotContain("Dark");
    };
    
    assertThat(yoda).isInstanceOfSatisfying(Jedi.class, jediRequirements);
    assertThat(luke).isInstanceOfSatisfying(Jedi.class, jediRequirements);