Why does a call to fail() compile in a Java Class

2019-06-28 00:32发布

问题:

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

回答1:

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.



回答2:

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



回答3:

This error is coming because your classname and annotation name are same(Test).Change your class name to 'Test1' or other than Test.