在我的 eclipse 项目中,我有一个 java 类,它使用重载方法验证不同类型的对象是否为空:
public class EmptyProof {
public static boolean isEmpty(String field) {
System.out.println("String " + field);
return field == null || field.trim().equals("");
}
public static boolean isEmpty(BigDecimal d) {
System.out.println("BI " + d.toString());
return d == null || d.compareTo(new BigDecimal("0")) == 0;
}
public static boolean isEmpty(Object input) {
System.out.println("obj " + input.toString());
return input == null || String.valueOf(input).length() == 0;
}
}
现在我想在 Spock 中编写一个单元测试:
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import spock.lang.Specification;
class EmptyProofSpec extends Specification {
def 'must evaluate emptiness of a String correctly'() {
expect: "isEmpty for String returns the right answer"
System.out.println("test string " + bi.toString());
EmptyProof.isEmpty(str as String) == result
where: "using this table"
str || result
"" || true
null || true
"a" || false
}
def 'must evaluate emptiness of a BigInteger correctly'() {
expect:
System.out.println("test BigInt " + bi.toString());
EmptyProof.isEmpty(bi as BigInteger) == result
where: "using this table"
bi || result
BigInteger.ONE || false
new BigInteger(Integer.MIN_VALUE) as BigInteger || false
// null as BigInteger || true
// BigInteger.ZERO as BigInteger || true
}
}
这会在控制台中显示以下输出:
test string
String
test string null
test string a
String a
test BigInt 1
obj 1
test BigInt -2147483648
obj -2147483648
正如您所看到的,我对 String 对象的测试调用了 isEmpty(String)。但我对 BigInteger 的调用不会调用 isEmpty(BigInteger) 而是调用 isEmpty(Object)。我想用 BigInteger.ZERO 添加测试,但这会失败,因为对象方法不关心 0。
我已经尝试过一些方法,例如强制转换和 @CompileStatic 注释。但没有成功。
我可以指示 Spock 使用 BigInteger 方法而不更改我的 Java 类吗?
最佳答案
它故障转移到 isEmpty(Object)
的原因是没有为 BigInteger
定义方法。存在的那个是为 BigDecimal
public static boolean isEmpty(BigDecimal d) { ... }
为 BigInteger
添加/编辑一个。
另请注意,null
情况将回退到 Object
。
关于java - 使用 spock 测试重载的 java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24740859/