Search code examples
groovyspock

Spock- Groovy call same client multiple times and assert the result


I am trying to test rate-limiter logic, it should result with too many request at the 6th trial

I want to get rid of the repetition of calling service 5 times and asserting 200 for the first 5 trial, but no luck, there is an exception Groovyc: Exception conditions are only allowed in 'then' blocks

def "POST request towards service is successfully limited"() {
   
    IntStream.range(1, 6).forEach({
        when:
        def result = client.post().uri("/test").exchange()

        then:
        noExceptionThrown()
        result != null
        result.expectStatus().isOk()
    })


    when:
    def result6 = client.post().uri("/test").exchange()

    then:
    noExceptionThrown()
    result6 != null
    result6.expectStatus().is4xxClientError()
}

Solution

  • Simply perform the first 5 calls and collect the results, then assert on the collected results.

    def "POST request towards service is successfully limited"() {
       
        when:
        def results = (1..5).collect { 
            client.post().uri("/test").exchange() 
        }
    
        then:
        results.size() == 5
        results.each {
          it.expectStatus().isOk()
        }
      
    
    
        when:
        def result = client.post().uri("/test").exchange()
    
        then:    
        result.expectStatus().is4xxClientError()
    }
    

    noExceptionThrown() is redundant, it should only be used when there are no other assertions in the then block.

    As you didn't post a compileable and runnable example, I cannot verify that this code works, but it should be close enough.