[英]test overloaded java methods with spock
在我的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在不更改Java类的情况下使用BigInteger方法吗?
它故障转移到isEmpty(Object)
的原因是因为没有为BigInteger
定义方法。 存在的一个是为BigDecimal
定义的
public static boolean isEmpty(BigDecimal d) { ... }
为BigInteger
添加/编辑一个。
还要注意, null
大小写将回退到Object
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.