Skip to content

Instantly share code, notes, and snippets.

@fumokmm
Created October 12, 2010 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fumokmm/622492 to your computer and use it in GitHub Desktop.
Save fumokmm/622492 to your computer and use it in GitHub Desktop.
// g100pon #61 GroovyTestCaseと各種拡張assertメソッド
---------------------------------------
$ groovy UtilTest.groovy
...
Time: 0.097
OK (3 tests)
// g100pon #61 GroovyTestCaseと各種拡張assertメソッド
class Util {
String utilName
def sum(int... x) {
if (!x) return 0
x.inject(0){ a, b -> a + b }
}
def sub(int... x) {
if (!x) return 0
def xs = x.toList()
xs.tail().inject(xs.head()){ a, b -> a - b }
}
def makeArray(Object... o) {
return o
}
@Override String toString() {
return "[${this.utilName}]"
}
}
// g100pon #61 GroovyTestCaseと各種拡張assertメソッド
//
// See: http://groovy.codehaus.org/Unit+Testing
// http://groovy.codehaus.org/api/groovy/util/GroovyTestCase.html
//
// Running GoovyTestCase on the command-line:
// $ groovy UtilTest.groovy
import groovy.util.GroovyTestCase
class UtilTest extends GroovyTestCase {
/** ユーティリティインスタンス */
def util
/** 事前準備 */
void setUp() {
util = new Util(utilName: 'TestUtil')
}
/** テストケース #sum() */
void testSum() {
assert 0 == util.sum()
assert 0 == util.sum(null)
assert 10 == util.sum(10)
assert 2 == util.sum(1, 1)
assert 6 == util.sum(1, 2, 3)
assert 55 == util.sum(1..10 as int[])
}
/** テストケース #sub() */
void testSub() {
assert 0 == util.sub()
assert 0 == util.sub(null)
assert 10 == util.sub(10)
assert 10 == util.sub(20, 10)
assert -5 == util.sub(20, 10, 15)
assert -5 == util.sub(5..1 as int[])
}
/** テストケース additional assertion methods */
void testMakeArray() {
assertArrayEquals(['a', 'b', 'c'] as String[], util.makeArray('a', 'b', 'c'))
assertArrayEquals([1, 2, 3] as Integer[], util.makeArray(1, 2, 3))
assertLength(5, util.makeArray('a'..'e' as char[]))
assertContains('o' as char, util.makeArray('Groovy' as char[]))
assertToString(util, '[TestUtil]')
assertInspect(util, '[TestUtil]')
// スクリプトが例外なしに終了するか
assertScript('''
def a = 10
def b = 20
def c = a + b
assert c == 30
''')
// クロージャが例外を投げるか
shouldFail {
1 / 0 // => divide by zero and thrown 'java.lang.ArithmeticException'
}
// クロージャが指定した例外を投げるか
shouldFail(java.lang.ArrayIndexOutOfBoundsException) {
def list = [1, 2, 3] as int[]
list[3]
}
shouldFail(java.lang.Exception) { // => 親例外でもOK
def list = [1, 2, 3] as int[]
list[3]
}
// クロージャが例外を投げ、かつ指定したクラスが再起的にcauseを辿った中に含まれるか
shouldFailWithCause(java.lang.ArithmeticException) {
try {
1 / 0 // => divide by zero and thrown 'java.lang.ArithmeticException'
} catch (Exception e) {
throw new Exception(new Exception(new Exception(e)))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment