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?

3
  • Did you try it? Also your answer is in that link. [stackoverflow.com/questions/21105403/… Commented Nov 4, 2015 at 6: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. Commented Nov 4, 2015 at 6:09
  • @ajb You mean the code is already doing this for the JUnit stuff :-) Commented Nov 4, 2015 at 6:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.