Reputation: 35
I have a little problem with a function used for testing. Here is my test method:
public static List<FieldError> proofFields(final List<String> fieldNames, final List<FieldError> errors, boolean fieldsAbsent){
List<FieldError> foundFields = errors.stream().filter(fieldError -> fieldNames.contains(fieldError.getField())).collect(toList());
if(fieldsAbsent){
assertTrue(foundFields.isEmpty());
} else {
assertTrue(fieldNames.size() == foundFields.size());
}
return foundFields;
}
It should check, if one list is (partially) contained in the other.
I would like to return the result, no matter if the test was successful or not. Is there a way to do this or does assertTrue/assertFalse always exit immediately?
Upvotes: 1
Views: 12128
Reputation: 5427
your method should return value or verify data.Don't mix it. You did it and now you have a problem :)
public static List<FieldError> proofFields(final List<String> fieldNames, final
List<FieldError> errors){
return errors.stream().filter(fieldError ->
fieldNames.contains(fieldError.getField())).collect(toList());
}
public static assertFieldWithError(final List<String> fieldNames, final
List<FieldError> errors){
assertEquals(fieldNames.size(), foundFields.isEmpty());
... iterate do more detail and check ....with assertXXXX();
}
public static assertFieldWithoutError(final
List<FieldError> errors){
assertTrue(foundFields.isEmpty());
}
also for construction like :
assertTrue(fieldNames.size() == foundFields.size())
better use
assertEquals(fieldsAbsent.size() , foundFields.size());
as it more informative way.
Upvotes: 2
Reputation: 140613
You can't have it both ways. You can't have your cake and eat it.
Either you are using one of the many JUnit 'asserts` - or you have code that doesn't throw exceptions.
Meaning: it is the nature of assert()
to throw when its condition is not met.
Thus the answer: you have to get clear on your requirements. If you want that test to throw in certain situations, then keep the asserts
in. If you want to return results always, then you remove those calls.
Upvotes: 2