*
The moose likes Design and the fly likes Are multiple 'when'/'then' blocks evil? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Engineering » Design
Bookmark "Are multiple Watch "Are multiple New topic
Author

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

Nic Grange
Greenhorn

Joined: Sep 04, 2013
Posts: 5
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

Joined: Aug 06, 2013
Posts: 33
    
    5
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

Joined: Oct 01, 2001
Posts: 814
    
    3
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


SCJP, SCJD, SCEA 5 "Any sufficiently analyzed magic is indistinguishable from science!" Agatha Heterodyne (Girl Genius)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Are multiple 'when'/'then' blocks evil?