I'm writing tests for my service and I faced an issue with RequestEntity.equals()
. I'm trying to check that my requests are equal, so I wrote this code:
var request = RequestEntity
.post("https://test.com/api/endpoint")
.header("Authorization", "Bearer")
.header("Cookie", "Cookie=cook;")
.body("Hello World", String.class);
var anotherRequest = RequestEntity
.post("https://test.com/api/endpoint")
.header("Authorization", "Bearer")
.header("Cookie", "Cookie=cook;")
.body("Hello World", String.class);
assert request.equals(anotherRequest);
But as a result I have this exception:
Exception in thread "main" java.lang.UnsupportedOperationException
at org.springframework.http.RequestEntity.getUrl(RequestEntity.java:165)
at org.springframework.http.RequestEntity.equals(RequestEntity.java:198)
at org.example.Application.main(Application.java:31)
As exception message suggests, I've checked .getUrl()
and .equals()
method in the RequestEntity
and found that .getUrl()
throws an exception when the url
field is null:
public URI getUrl() {
if (this.url == null) {
throw new UnsupportedOperationException();
}
return this.url;
}
but equals tries to compare objects in a null safe manner ObjectUtils.nullSafeEquals(getUrl(), otherEntity.getUrl()))
, like this:
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (!super.equals(other)) {
return false;
}
RequestEntity<?> otherEntity = (RequestEntity<?>) other;
return (ObjectUtils.nullSafeEquals(getMethod(), otherEntity.getMethod()) &&
ObjectUtils.nullSafeEquals(getUrl(), otherEntity.getUrl()));
}
That's clear from the code that the url
field can't be null otherwise you will get an exception. So, is this an expected behavior? How should I compare RequestEntity
objects?
Comment From: jhoeller
This looks like a duplicate of gh-27531 which we recently fixed. Please try it against 5.3.12, this should work out of the box now.