grails3 service测试

一、domain-class

package testservice

import grails.compiler.GrailsCompileStatic

@GrailsCompileStatic
class Student {

    String name
    BigDecimal grade
    Classroom classroom

    static constraints = {
        classroom nullable: true
    }
}

二、service

package testservice

import grails.gorm.transactions.Transactional

@Transactional(readOnly = true)
class StudentService {
//   返回grade大于传入值的数据
    List<Student> findStudentsWithGradeAbove(BigDecimal grade) {
        Student.findAllByGradeGreaterThanEquals(grade)
    }
// 返回所有的数据
    def finbyAll(){
        Student.list()
    }
}

三、找到service 对应的测试类


package testservice

import grails.testing.services.ServiceUnitTest

import grails.test.hibernate.HibernateSpec

@SuppressWarnings(['MethodName', 'DuplicateNumberLiteral'])

//grails框架自动生成的测试类继承的是Specification类,需要将之替换为HibernateSpec

class StudentServiceSpec extends HibernateSpec implements ServiceUnitTest<StudentService> {

    List<Class> getDomainClasses() { [Student] } // <1>
    def 'test find students with grades above'() {
        when: 'students are already stored in db'
//    先添加三条数据
     Student.saveAll(
                new Student(name: 'Nirav', grade: 91),
                new Student(name: 'Sergio', grade: 95),
                new Student(name: 'Jeff', grade: 93),
        )
//  then 后跟的为测试的内容
        then:
     Student.count() == 3

        when: 'service is called to search'
//    内置的service对象调用 findStudentsWithGradeAbove() 方法
    List<Student> students = service.findStudentsWithGradeAbove(92)

        then: 'students are found with appropriate grades'
        students.size() == 2
        students[0].name == 'Sergio'
        students[0].grade == 95
        students[1].name == 'Jeff'
        students[1].grade == 93
    }

    def 'test fin by all'() {
        when:
        Student.saveAll(
                new Student(name: 'Nirav', grade: 91),
                new Student(name: 'Sergio', grade: 95),
                new Student(name: 'Jeff', grade: 93),
        )

        then:
        Student.count() == 3

        when:
        def list = service.finbyAll()

        then:
        list.size() == 3
    }
}
4、运行
grails> test-app
grails> open test-reporttest-app 通过则显示 Tests PASSED,运行 open test-report 浏览器端查看测试详情

1.*grails框架自动生成的测试类继承的是Specification类,需要替换为HibernateSpec
2.*通过命令创建的domain class,controller,service,会自动生成其测试类,如果该类不需要测试请将其测试类删除或者删除测试类中所有的方法


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值