【问题标题】:Why do we need to import "org.junit.Assert " static? [duplicate]为什么我们需要导入“org.junit.Assert”静态? [复制]
【发布时间】:2020-02-02 11:26:33
【问题描述】:

我尝试在代码中输入assertTrue,发现需要导入junit lib。

在这段代码中,

import static org.junit.Assert.assertTrue;
//import org.junit.Assert;   with this didnt worked

public class Person implements Serializable {
       // some code there

        assertTrue(p2.getAge() == p.getAge());
        assertTrue(p2.getName().equals(p.getName()));
}

所以我尝试了import org.junit.Assert; 但是那个asserTrue没有用,然后我尝试了import static org.junit.Assert.assertTrue;,然后它就起作用了。我需要解释为什么需要静态?

【问题讨论】:

  • 您不必“必须”,您也可以只调用静态方法而无需静态导入
  • 不需要,imports是可选的,直接用org.junit.Assert.assertTrue(p2.getAge() == p.getAge());,也就是类/方法的全限定名...明显看起来更好,可读性更强, 使用导入

标签: java junit assert


【解决方案1】:

使用static 关键字,您可以使用方法而无需限定方法所属的类。请参阅文档中的相关部分:

静态导入构造允许对静态成员进行非限定访问,而无需从包含静态成员的类型继承。相反,该程序会导入成员 [...]

Static import

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    相关资源
    最近更新 更多