Spockでどのように優れた方法(例:データテーブル)で例外をテストできますか?Spock - データテーブルでの例外のテスト
例:異なるメッセージで例外をスローする、またはユーザーが有効な場合に例外をスローするメソッドvalidateUser
があります。
仕様クラス自体:
class User { String userName }
class SomeSpec extends spock.lang.Specification {
...tests go here...
private validateUser(User user) {
if (!user) throw new Exception ('no user')
if (!user.userName) throw new Exception ('no userName')
}
}
バリアント1
この1つは機能していますが、本当の意図がで雑然とされたすべてのとき/、その後ラベルとの繰り返しの呼び出しvalidateUser(user)
。
def 'validate user - the long way - working but not nice'() {
when:
def user = new User(userName: 'tester')
validateUser(user)
then:
noExceptionThrown()
when:
user = new User(userName: null)
validateUser(user)
then:
def ex = thrown(Exception)
ex.message == 'no userName'
when:
user = null
validateUser(user)
then:
ex = thrown(Exception)
ex.message == 'no user'
}
バリアント2この1が原因でコンパイル時にスポックが提起したこのエラーの動作していない
:
例外条件のみ「し、」ブロックに許可されている
def 'validate user - data table 1 - not working'() {
when:
validateUser(user)
then:
check()
where:
user || check
new User(userName: 'tester') || { noExceptionThrown() }
new User(userName: null) || { Exception ex = thrown(); ex.message == 'no userName' }
null || { Exception ex = thrown(); ex.message == 'no user' }
}
バリアント3
この1つがあるため、コンパイル時にスポックが提起したこのエラーの機能していません。
例外条件が唯一の推奨される解決策を持っているトップレベルの文
def 'validate user - data table 2 - not working'() {
when:
validateUser(user)
then:
if (expectedException) {
def ex = thrown(expectedException)
ex.message == expectedMessage
} else {
noExceptionThrown()
}
where:
user || expectedException | expectedMessage
new User(userName: 'tester') || null | null
new User(userName: null) || Exception | 'no userName'
null || Exception | 'no user'
}
は先週と同じシナリオに出くわしたと私は@peterを示唆している正確に何をしたの代わりにバニラのものや他のいくつかの「本当の」例外を使用します。 :) 1つのデータテーブルに基づいて例外(投げられた/ notThrown)の2つのvairantsを処理する方法ではありません。スローされた例外はデータテーブルにもありません。 – dmahapatro