Reputation: 4178
I am trying to write Spock Framework instead of Junit,
Test Class :
class StudentServiceSpec extends Specification{
@Shared def studentDao
@Shared def studentService
def setupSpec(){
studentDao = Mock(StudentDao)
studentService = new StudentService(studentDao)
}
def "Get Student Details Based on StudentId"(){
setup:
1*studentDao.getStudent(67) >> new Student()
when:
Response response = studentService.getStudent("67")
println "** Response "+response
println "** Response "+response.getEntity()
then:
response != null
}
}
When I Run the above code using maven clean install command, I am getting the following error.
Error :
1*studentDao.getStudent(67) >>> new Student() (0 invocations)
If I Use 0*studentDao.getStudent(67) >>> new Student()
I am Getting response.getEntity()
is null
Upvotes: 2
Views: 2247
Reputation: 4178
I have found my mistake...
I replaced the following code
@Shared def studentDao
@Shared def studentService
def setupSpec(){
studentDao = Mock(StudentDao)
studentService = new StudentService(studentDao)
}
with these two lines
StudentDao studentDao = Mock()
StudentService studentService = new StudentService(studentDao)
If we use @Shared
its mocking the class
but not mocking the method call
Upvotes: 3
Reputation: 675
There are many reasons that why this is not working.
One reason is that there might be inconsistencies with the data type of parameter you are using in the actual code and in the test. Say for example below
studentDao.getStudent(67)
check if your Dao method getStudent accepts long data type or int data type. That 67 might be treated as int in your spock test while in your actual code, the method getStudent only accepts long data type. Thus, failing to mock the call of studentDao.getStudent(67) to return new Student().
Other might be, the id was changed before the actual invocation of dao method getStudent
so.
As for the result with null
0*studentDao.getStudent(67) >>> new Student() I am Getting response.getEntity() is null
The null is expected since there is no mocking of your dao method to return Student object.
Upvotes: 0