精通 Grails: 测试 Grails 应用程序
编写第一个有价值的测试
以上是第一个正常运行的简单测试,接下来将展示一个更加实用的测试示例。假设您的 HotelStay 类有两个字段:Date checkIn 和 Date checkOut。根据一个用户情景,toString 方法的输出应该像这样:Hilton (Wednesday to Sunday)。通过 java.text.SimpleDateFormat 类,获取正确格式的日期非常简单。您应该为此编写一个测试,但不需验证 SimpleDateFormat 是否正确工作。您的测试做两件事情:它验证 toString 方法是否按照预期运行;它证明您是否满足用户情景。
将清单 5 中的代码输入到 HotelStay.groovy 和 HotelStayTests.groovy:
清单 5. 使用 assertToString
import java.text.SimpleDateFormat
class HotelStay {
String hotel
Date checkIn
Date checkOut
String toString(){
def sdf = new SimpleDateFormat("EEEE")
"${hotel} (${sdf.format(checkIn)} to ${sdf.format(checkOut)})"
}
}
import java.text.SimpleDateFormat
class HotelStayTests extends GroovyTestCase {
void testSomething(){...}
void testToString() {
def h = new HotelStay(hotel:"Hilton")
def df = new SimpleDateFormat("MM/dd/yyyy")
h.checkIn = df.parse("10/1/2008")
h.checkOut = df.parse("10/5/2008")
println h
assertToString h, "Hilton (Wednesday to Sunday)"
}
}
class HotelStay {
String hotel
Date checkIn
Date checkOut
String toString(){
def sdf = new SimpleDateFormat("EEEE")
"${hotel} (${sdf.format(checkIn)} to ${sdf.format(checkOut)})"
}
}
import java.text.SimpleDateFormat
class HotelStayTests extends GroovyTestCase {
void testSomething(){...}
void testToString() {
def h = new HotelStay(hotel:"Hilton")
def df = new SimpleDateFormat("MM/dd/yyyy")
h.checkIn = df.parse("10/1/2008")
h.checkOut = df.parse("10/5/2008")
println h
assertToString h, "Hilton (Wednesday to Sunday)"
}
}
输入 grails test-app 验证第二个测试是否通过。
testToString 方法使用了新的断言方法之一 —assertToString— 它由 GroovyTestCase 引入。使用 JUnit assertEquals 方法肯定会获得相同的结果,但是 assertToString 的表达能力更强。测试方法的名称和最终的断言清楚地表明了这个测试的目的(参见 参考资料 获得一个链接,它列出了 GroovyTestCase 支持的所有断言,包括 assertArrayEquals、assertContains 和 assertLength)。
0
相关文章