java - 使用 spock 测试重载的 java 方法

标签 java groovy overloading 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 使用 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/

相关文章:

java - Hazelcast Map 重启后 key 长度不同

java - 在 null 上找不到值类型为 java.lang.String 的属性 'android:text' 的 getter

grails - 如何在 grails 响应中添加状态消息

spring - 使用 RabbitMQ 插件在 Grails 中创建队列运行时

java - 在java中,我们可以通过传递父类(super class)方法中使用的参数的子类来覆盖方法吗?

java - 反向比较回文解(破解编码面试)

java - 如何在运行时更改 TextView 的样式

jenkins - 在Jenkinsfile中的哪里放置try/catch

java - 方法重载的基本概念是什么

JavaScript 相当于 Perl 的 AUTOLOAD