A thin layer over spring-test-mvc to make tests more spock-friendly
Spring mvc tests are great but the fluent API is not a naturally fit with spock.
This is why I created a very small layer over spring-test-mvc. It makes tests look nicer in groovy, using the capabilities of the language like JSON parsing.
By separating the requests from the assertions, we can use the spock DSL to write beautiful assertions.
Since most API use Json, the library is converting data to and from JSON directly. There is no support for other media types like XML.
My recommendation is to create a base class for your specifications
@ContextConfiguration(
loader = SpringApplicationContextLoader,
classes = [MyApplication]
)
abstract class AbstractMvcSpec extends SpockMvcSpec {
@Override
MockMvc buildMockMvc(WebApplicationContext wac) {
MockMvcBuilders.webAppContextSetup(wac).build()
}
}
class AuthenticationSpec extends AbstractMvcSpec {
def "unauthenticated users cannot get resource"() {
when:
def res = get('/api/simple')
then:
res.status == HttpStatus.FORBIDDEN
}
def "get session"() {
when:
def res = get('/api/session', new RequestParams(authToken: 'secretToken'))
then:
res.status == HttpStatus.OK
res.json.username == 'user'
}
def "post example"() {
when:
def res = post('/api/session', [someData: 'data'])
then:
res.status == HttpStatus.OK
res.json.data == 'data'
}
def "headers example"() {
when:
def res = post('/api/session', new RequestParams(headers: ['x-auth-token': 'token']))
then:
res.status == HttpStatus.OK
}
}
This lib depends on spock and groovy. If you use spring-boot the dependencies versions are optional.
Add the following to your build:
compile 'org.codehaus.groovy:groovy'
testCompile 'org.spockframework:spock-spring'
testCompile 'com.geowarin:spring-spock-mvc:0.2.1'
This package is hosted on jcenter
It is therefore available directly from a groovy grape.
You can also include the jcenter()
repository in your gradle script.
Or add a bunch of XML in your pom.xml.
MIT