Search code examples
javaassertj

AssertJ casting an extracted field to a Map


I have a Message object with MessageHeaders field. The MessageHeaders class implements a Map<String, Object>. I want to assert that I have specific headers set. I'm having trouble getting the MapAssert methods to come up.

Here's what I want to accomplish:

assertThat(actual)
  .extracting(Message::getHeaders) // This returns AbstractObjectAssert though
  .containsKeys("some key");  // Not available 

Here's the Message and MessageHeaders class to be clear:

public class Message {
  private MessageHeaders headers;
  // getter
}


public class MessageHeaders implements Map<String, Object>, Serializable {
  // methods
}

Solution

  • In order to use MapAssert you need to extract directly the MessageHeaders field and cast the extraction with asInstanceOf :

    assertThat(actual)
    .extracting("headers")
    .asInstanceOf(InstanceOfAssertFactories.MAP)
    .containsKey("some key");