TAGS :Viewed: 18 - Published at: a few seconds ago

[ Give a new lease of life to src/test/java ]

Before I start a quick question to all of you; So how many of you were excited to switch to new functional paradigm of programming in Java? I was very excited when I started learning the more declarative way of doing things. I liked the idea of telling what to do and not baby sit and tell how to do everything. I promised myself there is no going back to the old procedural style anymore. I was very happily replacing my old code with new found streams and lambdas. Until after writing all the new code and I sat to write test cases. That’s when euphoria faded away and I realised that I am back in the procedural world minutes after promising myself there is no going back. My simple test case was I need to verify that my method under test is returning 3 persons and I need to verify their names, gender and age. With the tools in hand I only came up with following code: List result = getPersons(); assertEquals(3, result.size()); for(Person person: result) { If(person.getName().equals(“Harry Potter”)) { // do 4 assertions for Harry Potter — Name, Gender, Age, hasMoney } If(person.getName().equals(“Ron Weasley”)) { // do 4 assertions for Ron Weasley } If(person.getName().equals(“Hermione Granger”)) { // do 4 assertions for Hermione Granger } } Or I thought of using Streams and filters but then test case quickly became as complex as the code being tested. And then I learned about AssertJ the fluent assertions library and boy I was impressed in first look. I can use fluent assertions to write my test code and no more procedural code. It was very easy to write the previous test in much better looking code with AssertJ. List result = getPersons(); assertThat(result).isNotEmpty() .hasSize(3) .extracting(Person::getName, Person::getAge, Person::getGender) .contains( tuple(“Harry Potter”, 11, “Male”), tuple(“Hermione Granger”, 12, “Female”), tuple(“Ron Weasley”, 13, “Male”) ); Clean, Precise and more importantly declarative. If you are still not impressed carry on reading.