I want to assert that expected
and actual
are equal to each other. It is ok if both are null
or blank (""
) -- i.e. null
means blank.
.withComparator(...).isEqualTo(expected)
does not work, because null
is checked before by AspectJ:
@Given("^data is \"([^\"]*)\"$")
void theDataIs(String arg) {
assertThat(msg.getData())
.usingComparator(blankOkComperator).isEqualTo(arg);
}
My comparator is Kotlin, but you get the idea:
object blankOkComperator : Comparator<String> {
override fun compare(o1: String?, o2: String?): Int {
if(StringUtils.isBlank(o1) && StringUtils.isBlank(o2)) return 0
if(StringUtils.isBlank(o1)) return -1
if(StringUtils.isBlank(o2)) return 1
return o1!!.compareTo(o2!!)
}
}
I only managed to implement the check by overriding AssertJ's Condition<String>
but it looks not very assert-j-ish to me:
@Given("^data is \"([^\"]*)\"$")
void theDataIs(String arg) {
assertThat(msg.getDate())
.is(new EqualToOrBothBlank(arg));
}
Again, the helper is Kotlin, but you know what I mean:
class EqualToOrBothBlank(val expected: String) : Condition<String?>() {
override fun matches(actual: String?): Boolean {
if(StringUtils.isBlank(actual) && StringUtils.isBlank(expected)) return true;
return StringUtils.equals(actual, expected)
}
}
Is there an AspectJ-way to implement the check?
At the moment you have to use a Condition
but it is a fair point for AssertJ not to check for null if one is using a specific comparator, I have created https://github.com/joel-costigliola/assertj-core/issues/1121 for that.
In the meantime, I would put the condition instance into a field to make the code more readable:
@Given("^data is \"([^\"]*)\"$")
void theDataIs(String arg) {
assertThat(msg.getDate()).is(equalToOrBothBlank(arg));
}
Oh and you are mentioning AspectJ instead of AssertJ a few times :D