Grails Spock GORM返回一个空列表

Grails Spock GORM返回一个空列表,grails,groovy,gorm,spock,Grails,Groovy,Gorm,Spock,我正在使用grailsgorm构建一个单元测试。当我调用list()方法接收数据时,列表返回空。 以下是控制器代码: println“entity=“+entity.get(1) NotificationProfile.List()的大小返回0 User.get(springSecurityService.principal.id)返回null 以下是规格代码: @Rollback @TestFor(NotificationProfileController) @Mock([Notificati

我正在使用grailsgorm构建一个单元测试。当我调用list()方法接收数据时,列表返回空。 以下是控制器代码: println“entity=“+entity.get(1)

NotificationProfile.List()的大小返回0 User.get(springSecurityService.principal.id)返回null

以下是规格代码:

@Rollback
@TestFor(NotificationProfileController)
@Mock([NotificationProfile, Entity, User])
class NotificationProfileControllerSpec extends Specification {

def setup() {
}

def cleanup() {
}

void "list by system admin"() {

    when:
    controller.springSecurityService = [principal: [id: 5]]
    controller.list()

    then:
    view == '/notificationProfile/list'

  }
 }

我会很高兴,如果我能在列表大小和非空用户良好的回报。谢谢。

当您进行单元测试时,Grails不使用您的数据库连接,因此,对于每个单元测试都没有数据

为了在正在运行的单元测试的生命周期内填充数据库,您需要在setup()方法中添加数据


模仿springSecurityService怎么样

import grails.plugin.springsecurity.SpringSecurityService
import grails.test.mixin.TestFor
import spock.lang.Specification
import spock.lang.Unroll

@TestFor(NotificationProfileController)
@Mock([NotificationProfile, Entity, User])
class NotificationProfileControllerSpec extends Specification {

    def springSecurityService

    def setup() {
        springSecurityService = Mock(SpringSecurityService)
        controller.springSecurityService = springSecurityService
    }

    void "list by system admin"() {
        given:
            User user = new User()
        when:
            controller.list()
        then:
            1 * springSecurityService.getPrincipal() >> user
        and:
            view == '/notificationProfile/list'
    }
}

成功了。谢谢。我认为在测试期间可以访问测试环境数据库。现在我可以做我的测试了。谢谢!
def setup() {
    // make sure you are creating a new user with all the required fields    
    // otherwise GORM will throw validation error
    new User(username: "test", email:"test@test.com").save flush:true, failOnError:true
}
import grails.plugin.springsecurity.SpringSecurityService
import grails.test.mixin.TestFor
import spock.lang.Specification
import spock.lang.Unroll

@TestFor(NotificationProfileController)
@Mock([NotificationProfile, Entity, User])
class NotificationProfileControllerSpec extends Specification {

    def springSecurityService

    def setup() {
        springSecurityService = Mock(SpringSecurityService)
        controller.springSecurityService = springSecurityService
    }

    void "list by system admin"() {
        given:
            User user = new User()
        when:
            controller.list()
        then:
            1 * springSecurityService.getPrincipal() >> user
        and:
            view == '/notificationProfile/list'
    }
}