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();
}
}
Regards,
Guido
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()
.
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();
}
}
Much more readable.
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.
This is perfectly correct and it will run and compile - I already checked using eclipse. The reason is the static import:
import static org.junit.Assert.*;
that adds all the static fields or methods from the org.junit.Assert class - hence including fail() method.
Nevertheless a problem that might occur is the fact that the name of your test class is the same as the name of the annotation
@Test
hence it will generate an error:
The import org.junit.Test conflicts with a type defined in the same file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With