【问题标题】:Test that confirms that the method signature has not been changed?确认方法签名未更改的测试?
【发布时间】:2019-07-06 21:26:56
【问题描述】:

这是一种假设情况。我使用 int 作为类型,但您可以随意将其替换为您选择的任何类型,这是一个关于如何编写确认没有人更改方法签名的测试的问题。

我编写了一个方法,它可以很好地处理整数,但如果它接收到某些非整数,就会产生非常难以追踪的错误。我想避免错误,所以我编写了一些测试来确认该方法是否正常工作。我正在用 Java 编写,所以我可以愉快地依赖 Java 的强类型。然而,总有一天,有人会想改变这种方法来接受一些非整数(可能是我),有时它会起作用(我会为自己感到非常自豪)。他们(我)甚至可能会编写一些测试来添加到他们改进的方法版本中,并且这些测试将通过,除非它们通过某些非整数。

是否可以编写一个测试来确认方法签名没有改变?

我已经尝试过了,但是myClass.multiply(2.0, 2); 无法编译,所以我无法运行测试。

import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.fail;

public class TestingCoercion {

    @Test
    public void multiply2x2() {
        MyClass myClass = new MyClass();
        Assert.assertEquals(myClass.multiply(2, 2), 4);
    }

    @Test
    public void multiplyDoesNotWorkWithFloat() {
        MyClass myClass = new MyClass();
        try {
            myClass.multiply(2.0, 2); //this line does not compile
            fail("MyClass.multiply is only for integers");
        } catch (Exception exception) {
            Assert.assertTrue("MyClass.multiply correctly rejected a double", true);
        }
    }


    class MyClass {
        public int multiply(int i, int j) {
            return i * j;
        }
    }
}

【问题讨论】:

  • "but myClass.multiply(2.0, 2); does not compile so I can't run the test.": 还不够可靠吗?如果其他开发人员可以更改方法签名,他们也可以更改单元测试或方法实现本身......

标签: java junit types casting type-conversion


【解决方案1】:

一种方法是使用反射来查找具有特定参数列表的特定方法。

你可以这样做:

try {
    MyClass.class.getMethod("multiply", int.class, int.class);
} catch (NoSuchMethodException) {
    // test has failed.
    fail(); //do not swallow this exception, fail the test
}

如果没有具有该确切参数列表的方法,getMethod 将抛出 NoSuchMethodException

如果您还想检查是否有人添加了您将来可能不小心调用的另一个重载,您也可以:

assertEquals(1, Arrays.stream(MyClass.class.getMethods()).filter(x -> x.getName().equals("multiply")).count());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-06
    • 2016-08-11
    • 1970-01-01
    • 2015-06-13
    • 2018-01-13
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多