2016-08-05 39 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對象的嘲諷。