一、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-report
test-app 通过则显示 Tests PASSED,运行 open test-report 浏览器端查看测试详情

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

标签:
在2019/04/27 04:02由Kevin Wu创建