In Groovy we can apply the @NullCheck
annotation to a class, constructor or method. The annotation is an AST (Abstract Syntax Tree) transformation and will insert code that checks for null values in methods or constructors. If a null
value is passed to an annotated method or constructor, it will throw an IllegalArgumentException
. Without the annotation we could have a NullPointerException
if we try to invoke a method on the value we pass as argument. The annotation has an optional property includeGenerated
which by default is false
. If we set it to true
then the null checks are also applied to generated methods and constructors. This is very useful if we apply other AST transformations to our class that generates additional code.
Continue reading →
The assertion error messages from AssertJ will use the toString()
method of an object to give more insight about why the assertion could have failed. If an object doesn’t override the toString()
method the default implementation is Object#toString()
. The default implementation will print out the class name and an hexadecimal value of hashCode
separated by a @
. This doesn’t give much information about the actual object. For classes we have control over we can always implement a toString()
method, but for third party classes we may not be able to do that. In order to customize how an object is represented in assertion error messages, AssertJ allows us to provide a custom representation class for an object. The custom representation class must implement the org.assertj.core.presentation.Representation
interface. The interface has one method String toStringOf(Object)
that should return a String representation of the object. If we want to keep the default behavior for other classes and only override it for our own class, we can extend the StandardRepresentation
class and override the method String fallbackToStringOf(Object)
.
Continue reading →
Since Java 16 we can use the method mapMulti(BiConsumer)
of the Stream
API. This method allows us to map each element of the stream to multiple elements. We can also do that with the flatMap(Function)
method, but if we want to map a limited set of elements, mapMulti
is more convenient. Internally a shared stream is used and we don’t have the cost of creating a new stream for each element. Another use case is if the logic to map an element to multiple elements is complex and is hard to implement by returning a stream. Then mapMulti
allows us to write that logic in a BiConsumer
instead of a Function
.
Continue reading →
For a lot of types AssertJ has special assertion methods. Also for the type Optional
. If we want to assert an Optional
value we can use several methods that AssertJ provides. For example to check if an Optional
is present we can use isPresent()
or the alias isNotEmpty()
. To check if the Optional
is empty we can use isEmpty()
or the alias isNotPresent()
. Checking the value of an Optional
(if it is indeed set) can be done with hasValue()
or contains()
. For more fine grained assertions on the value we can use hasValueSatisfying(Condition)
or hasValueSatisfying(Consumer)
. With the map(Function)
and flatMap(Function)
methods we can map the Optional
, if not empty, to another value and assert that value.
Continue reading →
AssertJ has a lot of custom assertion methods for different types. For example to assert an URL
object AssertJ gives us some specific methods.
We can check for different components of the URL
instance with different methods.
For example we can check if the protocol is equal to the protocol we expect with hasProtocol(String)
.
Similarly we can write assertions for the host, port, authority, path and anchor.
To assert query parameters we can use hasQueryParameter(String)
to check if query parameter is set and with hasQueryParameter(String, String)
we can check if the query parameter has an expected value.
To check the whole query string we can use hasQueryString(String)
.
Each of the assertion methods also has version to assert a component is not present.
For example hasNoQuery()
to assert a query is not defined for an URL
.
Continue reading →
AssertJ has some nice methods to verify string values. If we want to verify a string value is Base64 encoded we can use the isBase64String()
method. We can leave out the padding of the value as it is optional. With the method asBase64Decoded()
we can decode the value and write our assertions for the decoded value. The method asBase64Decoded()
returns a byte[]
object and we can use the asString()
to convert it into a string value again.
Continue reading →
To compare string values we can use the isEqualTo(String)
method in AssertJ. But if we want to verify that a string contains a certain variable value we can use string templates. This makes the assertion more readable as we can see what value we expect in the string. To use string templates we must the method isEqualTo(String, Object…)
. The first argument is the string template and the following arguments will be the actual values that should be used in the template. Actually the String.format(String, Object…)
method is used behind the scenes to format the string template, but we don’t have to clutter our assertions with that call.
Continue reading →
With the returns
method in AssertJ we can verify an object using a function. This allows us to verify an object in a very flexible way. We can chain multiple returns
method calls to verify multiple aspects of our object. The first argument of the returns
method is the expected value of the function call. And the second argument is a function that calls a method on the object we want to verify. A simple function call would be a method reference using the class of the object. But we can also write our own function, where the argument of the function is actual object we are writing the assertion for. To verify the function doesn’t return an expected value we can use the method doesNotReturn
.
We can also pass the function to the from
method, available in the Assertions
class. It can make the assertion more readeable as we can now read the code as: we expect the following value from calling this function.
Continue reading →
Writing assertions using the nice fluent API of AssertJ is a joy. Besides some of the basic assertions like isEqualTo
AssertJ also has specific assertions for specific types. For example if we want write an assertion to check if a String
value starts or ends with an expected value we can use the startsWith(String)
or endsWith(String)
methods. If we don’t care that a character is upper or lower case we can also use startsWithIgnoringCase(String)
or endsWithIgnoringCase(String)
. Each of the methods also has a counterpart method to check the String
value doesn’t start or end with an expected value. For example we can use doesNotStartWith(String)
to assert a value does not start with the expected value.
Continue reading →
AssertJ has many useful methods to write assertions using a fluid API. If we want to test the toString()
method implementation of an object we can of course invoke the toString()
method inside an assertThat
expression and check with the assert method isEqualTo(String)
the value. But AssertJ can make that easier so we don’t have to invoke toString()
method ourselves. We can use the assert method hasToString(String)
on the object we defined in the assertThat
expression and specify our expected value as argument to the method. If we want to assert the toString()
method doesn’t return an expected value we can use the assert method doesNotHaveToString(String)
.
Continue reading →
GINQ (Groovy-INtegerate Query) is part of Groovy since version 4. With GINQ we can use SQL-like queries to work with in-memory data collections. If we want to sort the data we can use orderby
followed by the property of the data we want to sort just like in SQL we can use order by
. By default the sort ordering is ascending and null
values are put last. We can change the sort ordering by specifying in desc
with the orderby
clause. Or to make the ascending order explicitly we use the statement in asc
. Each of asc
and desc
also can take an argument to specify how we want null
values to be sorted. The default way is to keep null
values last in the ordering. If we want to make this explicit we use nullslast
as argument to asc
or desc
. To have null
values in the sorted result first we use the argument nullsfirst
.
Continue reading →
Since Groovy 4 we can use SQL like queries on in-memory collections with GINQ (Groovy-Integrated Query). GINQ provides some built-in aggregate functions like min
, max
, sum
and others. One of these functions is median
. With median
we can get the value that is in the middle of the sorted list of values we want to calculate the median for. If the list has an uneven number of elements the element in the middle is returned, but if the list has an even number of elements the average of the two numbers in the middle is returned.
In the following example we see the use of the median
function with GINQ:
Continue reading →