我正在尝试对最终调用 Criteria API 的 distinct(Collection) 方法的服务方法进行单元测试(即,它调用采用 Collection 的 distinct() 版本)。我收到以下错误:
没有方法签名:greenfield224.BookService.distinct() 适用于参数类型:(java.util.ArrayList) 值:[[id, author, title, publisher]]
如果我更改服务方法,使其使用接受单个字符串属性名称的 distinct() 版本,我不会收到错误消息。但是,如果该单个属性名称是“id”,则它在单元测试中不返回任何内容。
我想知道这是否是 Grails 2.2.4 测试框架中的错误,或者我只是不理解某些东西。也许单元测试不支持使用 distinct() 方法?(顺便说一句,等效的集成测试可以正常工作)。下面是一些演示该问题的示例代码:
class Book {
Long id
String subject
String author
String publisher
String title
static constraints = {
subject nullable: true
author nullable: true
publisher nullable: true
title nullable: true
}
}
class BookService {
def findSimilarBooks(Book book) {
def results = Book.withCriteria {
eq('subject', book.subject)
order('title')
order('author')
projections {
//this line blows up in a unit test
distinct(['id', 'author', 'title', 'publisher'])
}
}
return results.collect {
[id:it[0], author:it[1], title:it[2], publisher:it[3]]
}
}
}
@TestFor(BookService)
@Mock(Book)
class BookServiceSpec extends Specification {
def "findSimilarBooks works properly"() {
setup:
def math = new Book(id:1, title:"Mathematics for Nonmathematicians", subject: "Math", author:"Morris Kline", publisher:"Somehouse")
def philosophy = new Book(id:2, title:"The Problems of Philosophy", subject: "Philosophy", author:"Bertrand Russell", publisher:"Ye Olde House of Mutton")
def investing = new Book(id:3, title:"The Intelligent Investor", subject: "investing", author:"Ben Graham", publisher:"Investors Anonymous")
def qed = new Book(id:4, title:"Q.E.D.", subject: "Math", author:"Burkard Polster", publisher: "Wooden Books")
def books = [math, philosophy, investing, qed]
books*.save(failOnError: true)
when:
def results = service.findSimilarBooks(math)
then:
results.size() == 2
}
}