如何使用Spock“ where”表测试重载方法

问题描述 投票:0回答:1

我想测试将null传递给这些重载方法:

public static Object someMethod(String n) { /* some impl */ }
public static Object someMethod(Integer n) { /* some impl */ }

我尝试过:

def "test someMethod"() {
    expect:
    someMethod(input) == expected
    where:
    input           | expected
    null as String  | someValue
    null as Integer | someValue
}

但是我得到了错误:

groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method com.foo.MyClass#someMethod.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:  
    [class java.lang.String]  
    [class java.lang.Integer]

如何使用一种spock方法在where块中输入空值(使用其他值)来测试这些?

groovy null spock
1个回答
1
投票

我正在尝试用Spock 1.3和Groovy 2.5.8重现您的问题,但不能。我还有另一个Spock问题,请参阅here。您必须使用其他版本的Spock和/或Groovy。

[无论如何,我刚刚链接到的Spock错误的一种解决方法是,不从then:expect:块调用带有null参数的方法,而是从when:调用该方法,并稍后在then:中进行比较块。另请参见我的代码示例。

[此外,您需要将特征方法分为两种方法,每种方法分别用于您要测试的null对象的类型。

正在测试的Java类:

package de.scrum_master.stackoverflow.q58279620;

public class ClassUnderTest {
  public static Object someMethod(String n) {
    return n == null ? "nothing" : "something";
  }

  public static Object someMethod(Integer n) {
    return n == null ? -999 : 11;
  }
}

Spock测试解决方法:

package de.scrum_master.stackoverflow.q58279620


import spock.lang.Specification
import spock.lang.Unroll

class PassingNullToOverloadedMethodTest extends Specification {
  @Unroll
  def "someMethod('#input') returns #expected"() {
    when:
    def result = ClassUnderTest.someMethod(input as String)

    then:
    result == expected

    where:
    input | expected
    "foo" | "something"
    ""    | "something"
    null  | "nothing"
  }

  @Unroll
  def "someMethod(#input) returns #expected"() {
    when:
    def result = ClassUnderTest.someMethod(input as Integer)

    then:
    result == expected

    where:
    input | expected
    0     | 11
    123   | 11
    null  | -999
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.