Skip to content

Commit e29c0c5

Browse files
author
Mariusz Kuligowski
committed
Add unit tests for controller
1 parent 8384da6 commit e29c0c5

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package com.baeldung.grails
2+
3+
import grails.testing.gorm.DomainUnitTest
4+
import grails.testing.web.controllers.ControllerUnitTest
5+
import spock.lang.*
6+
7+
class StudentControllerSpec extends Specification implements ControllerUnitTest<StudentController>, DomainUnitTest<Student> {
8+
9+
void "Test the index action returns the correct model"() {
10+
given:
11+
controller.studentService = Mock(StudentService) {
12+
list() >> [new Student(firstName: 'John',lastName: 'Doe')]
13+
}
14+
15+
when:"The index action is executed"
16+
controller.index()
17+
18+
then:"The model is correct"
19+
model.studentList.size() == 1
20+
model.studentList[0].firstName == 'John'
21+
model.studentList[0].lastName == 'Doe'
22+
}
23+
24+
void "Test the create action returns the correct model"() {
25+
when:"The create action is executed"
26+
controller.create()
27+
28+
then:"The model is correctly created"
29+
model.student!= null
30+
}
31+
32+
33+
void "Test the show action with a null id"() {
34+
given:
35+
controller.studentService = Mock(StudentService) {
36+
1 * get(null) >> null
37+
}
38+
39+
when:"The show action is executed with a null domain"
40+
controller.show(null)
41+
42+
then:"A 404 error is returned"
43+
response.status == 404
44+
}
45+
46+
void "Test the show action with a valid id"() {
47+
given:
48+
controller.studentService = Mock(StudentService) {
49+
1 * get(2) >> new Student(firstName: 'John',lastName: 'Doe')
50+
}
51+
52+
when:"A domain instance is passed to the show action"
53+
controller.show(2)
54+
55+
then:"A model is populated containing the domain instance"
56+
model.student instanceof Student
57+
and:"And student is John Doe"
58+
model.student.firstName == 'John'
59+
model.student.lastName == 'Doe'
60+
}
61+
62+
void "Test the delete action with an instance"() {
63+
given:
64+
controller.studentService = Mock(StudentService) {
65+
1 * delete(2)
66+
}
67+
68+
when:"The domain instance is passed to the delete action"
69+
request.contentType = FORM_CONTENT_TYPE
70+
request.method = 'DELETE'
71+
controller.delete(2)
72+
73+
then:"The user is redirected to index"
74+
response.redirectedUrl == '/student/index'
75+
}
76+
}
77+
78+
79+
80+
81+
82+

0 commit comments

Comments
 (0)