我使用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'
}
}
如果我能在列表大小和非空用户中获得良好的回报,我将很高兴。感谢。
答案 0 :(得分:1)
当您进行单元测试时,Grails不使用您的数据库连接,因此,对于每个单元测试,都没有数据。
为了在正在运行的单元测试的生命周期中填充数据库,您可以在setup()方法中添加数据。
datatime @dt = DATEADD(month, -6, DATEADD(month, DATEDIFF(month, 0, GETUTCDATE()), 0));
SELECT sUserAccount
FROM T_Operations WITH (readuncommitted)
WHERE dOperationValueDate < @dt
EXCEPT
SELECT sUserAccount
FROM T_Operations WITH (readuncommitted)
WHERE dOperationValueDate >= @dt;
答案 1 :(得分:0)
如何模拟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'
}
}