spock icon indicating copy to clipboard operation
spock copied to clipboard

Spock assertion inside if-statement doesn't work

Open lipnitsk opened this issue 5 years ago • 10 comments

See this blog post for a thorough analysis of the issue.

Given test case:

def "should fail on expected == result comparison"() {
    given:
    def expected = "Hello, John!"

    when:
    def result = "Hello, Joe!"

    then:
    if (expected) {
        expected == result
    }
}

Expected result: FAIL Actual result: PASS

lipnitsk avatar May 08 '20 21:05 lipnitsk

Is this meant as bug report or feature request?

Vampire avatar May 09 '20 22:05 Vampire

I'm not sure whether to call it a bug, but it has definitely caused missed test failures in my experience. At the very least, the current behavior is counterintuitive and error-prone

lipnitsk avatar May 09 '20 22:05 lipnitsk

Well, it is the expected and documented behavior. http://spockframework.org/spock/docs/1.3/all_in_one.html#_implicit_and_explicit_conditions clearly says

Except for calls to void methods and expressions classified as interactions, all top-level expressions in these blocks are implicitly treated as conditions. To use conditions in other places, you need to designate them with Groovy’s assert keyword

Besides that, personally I mostly never trust a test I did not see fail once. :-D

Vampire avatar May 09 '20 23:05 Vampire

You are right, it is documented, yet still error-prone. Any tips on how to enforce assertions on non-top-level conditions in a large test codebase? Is this completely out of scope for Spock and needs to be solved via CodeNarc or something similar?

lipnitsk avatar May 13 '20 20:05 lipnitsk

Well, do you have a good set of rules for verification? Just using any expression is bad too. Imagine for example expect: result.any { it != null }.

Vampire avatar Jul 22 '20 17:07 Vampire