Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Hamcrest matchers in a Spock specification
package com.grysz
import org.hamcrest.BaseMatcher
import org.hamcrest.CoreMatchers
import org.hamcrest.Description
import spock.lang.Specification
import spock.lang.Unroll
import static spock.util.matcher.HamcrestSupport.that
class HamcrestSpec extends Specification {
static messageSource = [
getMessage: { String code, Object[] args, Locale locale -> code }
]
@Unroll
def 'assertions without Hamcrest'() {
expect:
if (exactValue) {
assert field == exactValue
} else if (notAvailable) {
assert field == messageSource.getMessage('na', null, Locale.default)
} else if (isNumber) {
assert field.number
} else {
assert false, 'Wrong test configuration'
}
where:
field | exactValue | notAvailable | isNumber
'12345' | '12345' | null | null
'na' | null | true | null
'1' | null | null | true
}
@Unroll
def 'assertions with Hamcrest'() {
expect:
that field, verifiedBy
where:
field | verifiedBy
'12345' | CoreMatchers.equalTo('12345')
'na' | notAvailable()
'1' | isNumber()
}
@Unroll
def 'assertions with Hamcrest outside then or expect'() {
expect:
verifyField field, verifiedBy
where:
field | verifiedBy
'12345' | CoreMatchers.equalTo('12345')
'na' | notAvailable()
'1' | isNumber()
}
private notAvailable() {
CoreMatchers.equalTo messageSource.getMessage('na', null, Locale.default)
}
private isNumber() {
[
matches: { actual -> actual.number },
describeTo: { Description description -> 'should be a number' }
] as BaseMatcher
}
private void verifyField(actual, verifiedBy) {
assert that(actual, verifiedBy)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.