Learning AssertJ: Null ain't Blank

Popular assertions framework AssertJ surprises Java engineers with handling NULL-values different from what is commonly expected

· Software Engineering · Updated
By Jan Brennenstuhl · 2min read

Learning AssertJ: Null ain't Blank

Try it yourself: Google “how to check for blank string” – I got about 44 million results. Strings are probably the most common data structures we programmers hand around. In the cross-language String-environment there are well established meanings and commonly shared understandings.

Especially when it comes to the well-known difficulties regarding null strings vs empty strings (and blank strings) it is worth for everyone to follow already wide-spread naming conventions.

Toilet rolls representing blank and null states

With Apache Commons StringUtils and Hibernate Validator Constraints two popular and widely adapted projects already established a de-facto definition for a blank string:

“A blank String is a CharSequence that is empty (""), null or whitespace only.”

While recently investigating a bug in one of our systems, I stumbled upon a slight divergent and unexpected string handling in AssertJ, a fluent assertions framework for Java. This AssertJ misbehavior has potential to lead to severe troubles – which is why I would argue it’s a bug. As it turns out …

String s = null;
assertThat(s).isNotBlank();

… passes. This is definitely not expected behavior, since (following the definition above) a null string is commonly considered to be a blank string and vise-versa. So if you’re also used to Apache Commons StringUtils and Hibernate Validators behavior, you wanna make sure your tests actually also expect the correct behavior.

Do you know further libraries that follow a different blank string definition or if you have a different opinion about all of this, drop me message via Twitter!

Portrait of Jan Brennenstuhl
Written by Jan Brennenstuhl

Jan Brennenstuhl is a Principal Software Engineer, balancing security with friction for users. He helped building an IAM team and spent years in engineering single sign-on (SSO) solutions based on OIDC.