0

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()
}
Vy Do
  • 46,709
  • 59
  • 215
  • 313
curious
  • 231
  • 3
  • 12
  • https://stackoverflow.com/questions/10910080/how-can-i-repeat-spock-test – daggett Jan 03 '22 at 19:14
  • thanks @daggett, i already saw this post, but it always expect integer, somehow i could not manage to apply same thing for my use case – curious Jan 03 '22 at 19:27

1 Answers1

1

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.

Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66