Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 211
Guido Anselmi Avatar asked Nov 29 '22 08:11

Guido Anselmi


2 Answers

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.

like image 174
Platinum Azure Avatar answered Dec 04 '22 16:12

Platinum Azure


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

like image 23
Olimpiu POP Avatar answered Dec 04 '22 17:12

Olimpiu POP