Search code examples
javaconditional-statementsassertj

AssertJ result feedback with "iterable asserts"


I'm checking that a list of Strings contains a specific number meeting a certain condition, specifically that they contain a substring, ignoring case.

So I came up with this (reasons for the failedResults field will become apparent):

    class ContainsIgnoringCase extends Condition<CharSequence> {
        private String lCString;
        private int failedResults = 0;
        int getFailedResults(){
            return failedResults;
        }

        ContainsIgnoringCase( String string ){
            lCString = string.toLowerCase();
        }

        @Override
        public boolean matches( CharSequence value ) {
            boolean result = value.toString().toLowerCase().contains( lCString );
            if( ! result ){
                failedResults++;
            }
            return result;
        }
    }

If this then fails:

    assertThat( paramsPassed ).haveExactly( 7, new ContainsIgnoringCase( "documents" ));

it prints out the List<String> paramsPassed, but it doesn't say the actual number of failures.

I thought this might possibly do the trick, but it doesn't:

    ContainsIgnoringCase cic = new ContainsIgnoringCase( "documents" );
    assertThat( paramsPassed ).as( "failed: " + cic.getFailedResults() ).haveExactly( 7, new ContainsIgnoringCase( "documents" ));

... this just prints "failed 0", so obviously the method getFailedResults() is called before the test is carried out. Somewhere inside the guts of AssertJ this failure figure must have been computed... is there any way of printing it out for the user?


Solution

  • Add a toString to your condition like this one for example:

        @Override
        public String toString() {
            return "elements containing '" + this.lCString + "' but it failed for " + getFailedResults();
        }
    

    given paramsPassed = list("documents", "2"); it will give an error like :

    Expecting elements:
    <["documents", "2"]>
     to have exactly 7 times <elements containing 'documents' but failed = 1>