AssertJ casting an extracted field to a Map
Asked Answered
O

3

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
}
Overkill answered 20/8, 2019 at 21:10 Comment(0)
S
24

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");
Stethoscope answered 21/8, 2019 at 21:13 Comment(2)
asInstanceOf() was introduced in AssertJ Core 3.13.0 Release. I will have to update.Overkill
It changed to isInstanceOf()Russo
P
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.

Penis answered 29/8, 2019 at 5:0 Comment(0)
O
0

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

assertThat(actual.getHeaders())
  .containsKey("some key");
Overkill answered 21/8, 2019 at 20:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.