Why fail () call compiles in java class using JUnit

It seems that it should not compile and run, since Object does not have a fail() method. Is something scared going on during compilation? (I am using NetBeans):

 import static org.junit.Assert.*; import org.junit.Test; public class Test { @Test public void hello() { fail(); } } 

Hello,

Guido

+4
source share
3 answers

Your import static line imports all the static members of the Assert class into the static namespace of your compilation unit. The fail() call refers to Assert.fail() .

The confusion you face regarding the definition of fail() , which is why I usually do not recommend using import static . In my own code, I usually import the class and use it to call 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 a fairly common practice to use import static for JUnit statements; when you write and read enough JUnit tests, knowing where the approval methods come from will become second nature.

+18
source

This is completely correct and it will be launched and compiled - I already checked with eclipse. The reason is static import:

 import static org.junit.Assert.*; 

which adds all static fields or methods from the org.junit.Assert class, so it includes the fail () method.

However, a problem may occur that the name of your test class matches the name of the annotation

 @Test 

therefore, it will generate an error:

Import error org.junit.Test in conflict with a type defined in the same file

+6
source

This error occurs because the name of your name and the name of the annotation are the same (Test). Change your class name to "Test1" or something other than Test.

0
source

All Articles