Spock – 使用数据表测试异常
发布时间:2020-12-14 16:38:57 所属栏目:大数据 来源:网络整理
导读:如何用Spock以一种不错的方式(例如数据表)来测试异常? 示例:具有可以使用不同消息抛出异常的方法validateUser,如果用户有效则没有异常。 规范类本身: class User { String userName }class SomeSpec extends spock.lang.Specification { ...tests go her
如何用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 这一个是工作,但真正的意图是凌乱的所有when / then标签和validateUser(用户)的重复调用。 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 这个不工作,因为Spock在编译时引发的错误: 异常条件只允许在’then’块中 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 这个不工作,因为Spock在编译时引发的错误: 异常条件仅允许作为顶级语句 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' } 解决方法
推荐的解决方案是有两种方法:一种测试好的情况,另一种测试坏的情况。然后这两种方法都可以使用数据表。
例: class SomeSpec extends Specification { class User { String userName } def 'validate valid user'() { when: validateUser(user) then: noExceptionThrown() where: user << [ new User(userName: 'tester'),new User(userName: 'joe')] } def 'validate invalid user'() { when: validateUser(user) then: def error = thrown(expectedException) error.message == expectedMessage where: user || expectedException | expectedMessage new User(userName: null) || Exception | 'no userName' new User(userName: '') || Exception | 'no userName' null || Exception | 'no user' } private validateUser(User user) { if (!user) throw new Exception('no user') if (!user.userName) throw new Exception('no userName') } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |