当前位置:K88软件开发文章中心编程语言JavaGroovy → 文章内容

Groovy 单元测试

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-15 15:50:04

由 lichiabor 创建,小路依依 最后一次修改 2016-12-12 面向对象系统的基本单元是类。因此单元测试由一个类中的testig组成。所采用的方法是创建被测试类的对象,并使用它来检查所选方法是否按预期执行。不是每个方法都可以测试,因为并不总是测试每一件事情。但是应该对关键和关键方法进行单元测试。 JUnit是一个开源测试框架,是Java代码自动化单元测试的公认行业标准。幸运的是,JUnit框架可以很容易地用于测试Groovy类。所需要的只是扩展作为标准Groovy环境一部分的GroovyTestCase类。 Groovy测试用例类基于Junit测试用例。编写一个简单的Junit测试用例假设我们在应用程序类文件中定义了以下类:class Example { static void main(String[] args) { Student mst = new Student(); mst.name = "Joe"; mst.ID = 1; println(mst.Display()) } } public class Student { String name; int ID; String Display() { return name +ID; } }低于上述程序的输出中给出。 Joe1现在假设我们想为Student类写一个测试用例。典型的测试用例如下所示。以下几点需要注意以下代码 - 测试用例类扩展了GroovyTestCase类我们使用assert语句来确保Display方法返回正确的字符串。class StudentTest extends GroovyTestCase { void testDisplay() { def stud = new Student(name : 'Joe', ID : '1') def expected = 'Joe1' assertToString(stud.Display(), expected) }} Groovy测试套件通常,随着单元测试的数量增加,将难以一个接一个地继续执行所有测试用例。因此,Groovy提供了一个创建测试套件的工具,可以将所有测试用例封装到一个逻辑单元中。以下代码段显示了如何实现这一点。应该注意以下事情的代码 - GroovyTestSuite用于将所有测试用例封装在一起。在下面的例子中,我们假设我们有两个测试用例文件,一个叫StudentTest,另一个是EmployeeTest,它包含所有必要的测试。 import groovy.util.GroovyTestSuite import junit.framework.Test import junit.textui.TestRunner class AllTests { static Test suite() { def allTests = new GroovyTestSuite() allTests.addTestSuite(StudentTest.class) allTests.addTestSuite(EmployeeTest.class) return allTests } } TestRunner.run(AllTests.suite())

Groovy 单元测试