【问题标题】:Spock 'throw new Exception()' feature not workingSpock“抛出新异常()”功能不起作用
【发布时间】:2018-09-01 18:55:37
【问题描述】:

我正在尝试在 Spock 中使用 {throw new Exception()},但在运行测试时它会打印在报告中--

“出现以下问题: 'java.lang.Exception' 类型的预期异常,但未引发异常”

package testing

import spock.lang.Specification

class MyFirstSpec extends Specification {
    def "Test_One" (){

                given:              
                    def obj = new SpockMethodsPlaceholder()
                    obj.returnAge(0) >> {throw new Exception("invalidAge")}
                when:
                    1*obj.returnAge(0)
                then:
                    Exception ex = thrown()
                    ex.getMessage() == "invalidAge"

            }

        class SpockMethodsPlaceholder {
            def "returnAge" (int age){
                return age
            }
        }   
}

我的代码有问题吗?

下面是测试运行的堆栈跟踪---

工作目录: Gradle 用户主页:/home/mafia/.gradle Gradle Distribution:来自目标构建的 Gradle 包装器 梯度版本:4.3 Java 主页:/usr/lib/jvm/java-8-oracle JVM 参数:无 程序参数:无 已启用构建扫描:false 启用离线模式:false 测试:testing.MyFirstSpec

:compileJava UP-TO-DATE :compileGroovy 无源 :processResources 无源 :classes UP-TO-DATE :compileTestJava :compileTestGroovy :processTestResources 无源 :testClasses :测试

testing.MyFirstSpec > Test_One 失败 org.spockframework.runtime.WrongExceptionThrownError at MyFirstSpec.groovy:16

1 个测试完成,1 个失败 有失败的测试。请参阅报告:file:///media/mafia/A08200E98200C62E/Study/Git_Repo/GIT_JAVA/workbench/SpockProject/build/reports/tests/test/index.html

在 19 秒内构建成功 4 个可操作的任务:3 个已执行,1 个是最新的

【问题讨论】:

    标签: spock


    【解决方案1】:

    您似乎误解了存根/模拟的概念

    究竟测试了什么?班级SpockMethodPlaceholder?在这种情况下,它不应该被模拟/存根,它是一个“被测类”——你检查并希望获得它工作的信心的代码(如果你愿意,这个类的方法中的代码)

    另一方面,如果您使用>> 语法,您可能确实打算存根一些东西。

    所以这是一个更好的例子:

    public class SomeClass {
       public int return getAge(int age) {
         if(age <= 0) {
             throw new IllegalArgumentException("too young");
         } else {
           return age;
         }
       }
    }
    
    
    class SomeClassTest extends Specification {
    
      def "an exception is thrown if the person is too young" () {
         given:
           def subject = new SomeClass()
         when:
            subject.getAge(-1)
         then:
            def ex = thrown(IllegalArgumentException)
            ex.message == "too young" 
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-25
      • 2014-05-10
      • 2012-10-24
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 2015-07-10
      相关资源
      最近更新 更多