Skip to content

Instantly share code, notes, and snippets.

@jonreeve
Last active March 29, 2018 02:38
Show Gist options
  • Save jonreeve/777474ec490da32f8d83 to your computer and use it in GitHub Desktop.
Save jonreeve/777474ec490da32f8d83 to your computer and use it in GitHub Desktop.
Spek examples in Spock or JUnit + Hamcrest
// For first example on Spek site:
// Define a field for the SUT on the spec class:
def calculator = new Calculator()
// then your Spock test body is just this:
expect:
calculator.sum(2, 4) == 6
// and in JUnit with Hamcrest it would be this:
assertThat(calculator.sum(2, 4), equalTo(6))
// I can read those much more easily and no comments required.
// For the more interesting next example, firstly I'd argue that the API isn't great, because
// calculateRate(200, 10) is very unclear without named parameters, but anyway...
// Define the field for the SUT on the spec class:
def taxRateCalculator = new TaxRateCalculator()
// then the Spock test body is:
given:
def income = 200
def changeRate = 10
expect:
taxRateCalculator.calculateRate(income, changeRate) == 300
// or perhaps:
expect:
taxRateCalculator.calculateRate(income, changeRate) == expectedRate
where:
income | changeRate | expectedRate
200 | 10 | 300
// I'd argue that either of these can be read as a clear spec, with no comments.
// In JUnit with Hamcrest:
// given
int income = 200
int changeRate = 10
assertThat(taxRateCalculator.calculateRate(income, changeRate), equalTo(300))
// Again, I'd argue that's perfectly readable without comments. So to me, adding comments
// carries the same burden as with adding them to code. I would do it only as a last resort if I felt
// I couldn't make the code readable enough on its own, because code can change when the comment doesn't,
// code can be wrong when the comment is right, and it makes it easy to overlook the actual code when the comment
// seems correct but the code isn't.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment