【问题标题】:Grails Spock GORM returns an empty listGrails Spock GORM 返回一个空列表
【发布时间】:2016-10-06 13:23:45
【问题描述】:

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

    println "list = "+NotificationProfile.list().size()

    params.max = Math.min((params.max as Integer) ?: 10, 100)
    User user = User.get(springSecurityService.principal.id)

    println "user = "+user

NotificationProfile.List().size 返回 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 groovy grails-orm spock


    【解决方案1】:

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

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

    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
    }
    

    【讨论】:

    • 成功了。非常感谢。我认为可以在测试期间访问测试环境数据库。现在我可以做我的测试了。非常感谢!
    【解决方案2】:

    模拟 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'
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多