• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Are multiple 'when'/'then' blocks evil?

 
Nic Grange
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BDD framework 'Spock' allows you to specify multiple 'when'/'then' blocks but should they be used or are they evil?

I've seen a person using it but it doesn't look right as it seems it should be broken down into multiple tests.
The specific scenario was writing a specification to delete a file. The first when/then creates to the files to be deleted and checks it exists then the second when/then deletes the file and check it doesn't exist.

 
John Smart
Author
Ranch Hand
Posts: 43
5
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, multiple separate when/then blocks are pretty bad news, particularly for unit tests. A Spock specification, like an ordinary JUnit test, should try to just verify a single concept. For the example you did, the first when/then sounds like a precondition rather than a real check. Maybe something like this:

@TempDir File tempDir

def "should delete a file"() {
given:
def someFile = new File(tempDir,"somefile.txt")
and:
someFile.exists()
when:
someFile.delete()
then:
!someFile.exists()
}
 
Burk Hufnagel
Ranch Hand
Posts: 814
3
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nic Grange wrote:BDD framework 'Spock' allows you to specify multiple 'when'/'then' blocks but should they be used or are they evil?

I've seen a person using it but it doesn't look right as it seems it should be broken down into multiple tests.
The specific scenario was writing a specification to delete a file. The first when/then creates to the files to be deleted and checks it exists then the second when/then deletes the file and check it doesn't exist.

I agree with John. Logically, it makes sense to me that the file creation should be part of the 'given'.

To me, having multiple when/then blocks is the TDD equivalent of testing more than one thing in a test method. It might make sense sometimes, but when the test fails you don't know why and you've got to figure out which part actually failed instead of knowing right away. Testing one thing at a time makes it much easier.

Burk
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic