为了账号安全,请及时绑定邮箱和手机立即绑定

确认方法签名未更改的测试?

确认方法签名未更改的测试?

守着星空守着你 2022-06-15 17:20:14
这是一种假设情况。我使用 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;        }    }}
查看完整描述

1 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

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


你可以这样做:


try {

    MyClass.class.getMethod("multiply", int.class, int.class);

} catch (NoSuchMethodException) {

    // test has failed.

    fail(); //do not swallow this exception, fail the test

}

getMethodNoSuchMethodException如果没有具有该确切参数列表的方法,将抛出一个。


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


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



查看完整回答
反对 回复 2022-06-15
  • 1 回答
  • 0 关注
  • 222 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号