9

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
}
George
  • 2,820
  • 4
  • 29
  • 56

3 Answers3

20

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");
jota3
  • 5,389
  • 2
  • 13
  • 22
7

AssertJ Core 3.14.0 provides a new extracting() to support direct casting, so you can write:

assertThat(actual)
  .extracting(Message::getHeaders, as(InstanceOfAssertFactories.MAP))
  .containsKey("some key");

Note that as() is an optional syntax sugar to improve readability.

Stefano Cordio
  • 1,687
  • 10
  • 20
0

The solution / workaround I came up with was to assert the map itself instead of using extracting.

assertThat(actual.getHeaders())
  .containsKey("some key");
George
  • 2,820
  • 4
  • 29
  • 56