0

Is it possible to call a static method from a junit test without specifying it's class?

The following code works:

package lightsOut;

import static org.junit.Assert.*;
import org.junit.Test;
import lightsOut.LightsOutModel;

public class LightsOutModelTest {

    @Test
    public void testLightsOutModel1(){
        assertTrue(LightsOutModel.checkWin()); // Note here
    }

}

But when I remove the class from the following line it shows an error.

        assertTrue(checkWin()); // Note here

The error is:
The method checkWin() is undefined for the type LightsOutModelTest

Do I always have to specify the class on the static method call? Isn't there a way to import all the methods from the class because the way I tried to do it doesn't seem to work?

spencer.sm
  • 19,173
  • 10
  • 77
  • 88
  • Did you try it? Also your answer is in that link. [http://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito] – Thanh Duy Ngo Nov 04 '15 at 06:08
  • 1
    `import static lightsOut.LightsOutModel.checkWin;`. The interesting thing is that your code already does this. That's why you don't need to specify the class to call `assertTrue`. – ajb Nov 04 '15 at 06:09
  • @ajb You mean the code is already doing this for the JUnit stuff :-) – Tim Biegeleisen Nov 04 '15 at 06:10

1 Answers1

2

You need to use a static import of the method:

import static lightsOut.LightsOutModel.checkWin;

Once you import, you can directly use them,

checkWin();

Here is the official reference

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56