为什么JUnit在Java中断言方法不通用? [英] Why are JUnit assert methods not generic in Java?

查看:106
本文介绍了为什么JUnit在Java中断言方法不通用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JUnit 4.12。断言方法本质上不是通用的。例如,assertEquals方法如下所示:

I am using JUnit 4.12. The assert methods are not generic in nature. For instance, assertEquals method looks like:

static public void assertEquals(Object expected, Object actual) {..}

为什么不喜欢?

static public <T> void assertEquals(T expected, T actual) {..}

我觉得需要通用方法声明更好的编译时间检查和IDE自动完成。

I felt need for generic method declaration for better compile time checking and IDE auto completion.

推荐答案

拥有这样的通用方法:

<T> void assertEquals(T expected, T actual) { /* ... */ }

给你no类型安全,以避免比较不同的类型:你可以传递任何东西到这个方法,因为 T 退化到它的上限,对象

gives you no type safety to avoid comparing unlike types: you can pass in anything to this method, since T degenerates to its upper bound, Object:

assertEquals("string", 0);  // Compiles fine, even though they can't be equal.

Ideone demo

你也不能在预期上使用任何方法和对象上找不到的实际。所以, T 基本上只是对象

And nor can you use any methods on expected and actual that aren't found on Object. So, T is basically just Object.

As这样,添加泛型只会使实现过于复杂。

As such, adding generics is just over-complicating the implementation.

现在,你可以定义一个这样的类:

Now, you could define a class like this:

class GenericAssert<T> {
  void assertEquals(T expected, T actual) { /* ... */ }
}

你可以使用它:

new GenericAssert<String>().assertEquals("string", 0);  // Compiler error.

因为您现在已经在的可接受参数上设置了更严格的上限assertEquals ,在班级。

because you've now placed a tighter upper bound on the acceptable parameters of assertEquals, at class level.

但这只是感觉有点尴尬。

But this just feels a bit awkward.

这篇关于为什么JUnit在Java中断言方法不通用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆