2016-08-05 55 views
1

我想写斯波克框架,而不是JUnit中,嘲讽没有出现在斯波克工作框架

测试类:

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 
    } 
} 

当我使用maven干净的安装命令运行上面的代码,我得到以下错误。

错误:

1*studentDao.getStudent(67) >>> new Student() (0 invocations) 

如果我使用0*studentDao.getStudent(67) >>> new Student() 我得到response.getEntity()null

回答

2

我发现我的错误...

我换成下面的代码

@Shared def studentDao 
@Shared def studentService 

def setupSpec(){ 
studentDao = Mock(StudentDao) 
studentService = new StudentService(studentDao) 
} 

与这两条线

StudentDao studentDao = Mock() 
StudentService studentService = new StudentService(studentDao) 

如果我们使用@Shared其嘲讽class但不是嘲笑method call

+0

你可以接受你的自己的回答 – kazanaki

+0

哇,你救了我的夜晚:) thx – radio

0

有许多原因,为什么这是行不通的。

一个原因是可能与您在实际代码和测试中使用的参数的数据类型不一致。举例来说,如下所示

studentDao.getStudent(67) 

检查您的Dao方法getStudent是否接受长数据类型或int数据类型。在你的spock测试中,67可能被视为int,而在你的实际代码中,getStudent方法只接受长数据类型。因此,未能嘲笑studentDao.getStudent(67)的调用返回新的Student()。

其他可能,该ID是道法getStudent

这样的实际调用之前改变。

  1. 检查,如果数据类型参数的studentDao.getStudent(_)它的长,尝试67L在您的测试
  2. 检查,如果有其他代码的DAO方法
的调用之前修改ID

至于与空

0*studentDao.getStudent(67) >>> new Student() I am Getting response.getEntity() is null 

结果空预期,因为没有你的DAO方法返回Student对象的嘲讽。