问题描述
这似乎不应该编译和运行,因为Object
没有fail()
方法.在编译时发生了什么时髦的事情? (我正在使用NetBeans):
This seems like it shouldn't compile and run as Object
does not have a fail()
method. At compile time is something funky happening? (I am using NetBeans):
import static org.junit.Assert.*;
import org.junit.Test;
public class Test {
@Test
public void hello() {
fail();
}
}
此致
Guido
推荐答案
您的import static
行将Assert
类的所有静态成员导入到编译单元的静态名称空间中. fail()
调用引用Assert.fail()
.
Your import static
line imports all static members of the Assert
class into the static namespace of your compilation unit. The fail()
call refers to Assert.fail()
.
您对定义fail()
的位置所遇到的困惑正是为什么我通常不建议使用import static
的原因.在我自己的代码中,我通常导入该类并使用它来调用静态方法:
The confusion you are experiencing regarding where fail()
is defined is precisely why I don't usually recommend using import static
. In my own code, I usually import the class and use it to invoke the static methods:
import org.junit.Assert;
import org.junit.Test;
public class Test {
@Test
public void hello() {
Assert.fail();
}
}
更具可读性.
但是,作为,将import static
用于JUnit的断言是相当普遍的做法.当您编写和阅读足够的JUnit测试时,知道断言方法的来源将成为第二自然.
However, as JB Nizet points out, it is fairly common practice to use import static
for JUnit's assertions; when you write and read enough JUnit tests, knowing where the assertion methods come from will become second nature.
这篇关于为什么使用JUnit在Java类中编译对fail()的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!