Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java jUnit: Test suite code to run before any test classes

Tags:

I have a test suite class:

@RunWith(Suite.class) @Suite.SuiteClasses({     GameMasterTest.class,     PlayerTest.class, }) public class BananaTestSuite {  

What annotation do I need to use to make a function in this class run before any of the classes containing actual tests? Right now, I'm doing this, and it works, but it's not as readable as it could be:

static {     try {         submitPeelAction = new Player(new GameMaster(1)).getClass().getDeclaredMethod("submitPeelAction");     } catch (SecurityException e) {         e.printStackTrace();     } catch (NoSuchMethodException e) {         e.printStackTrace();     }     submitPeelAction.setAccessible(true); } 

I tried @BeforeClass but it didn't work.

like image 842
Nick Heiner Avatar asked Dec 27 '09 22:12

Nick Heiner


People also ask

Will execute the method once before the start of all tests?

It is possible to run a method only once for the entire test class before any of the tests are executed, and prior to any @Before method(s). “Once only setup” are useful for starting servers, opening communications, etc. It's time-consuming to close and re-open resources for each test.


2 Answers

Make a super test class containing the method annotated with @BeforeClass. Extend all the test classes from this class, eg,

@Ignore public class BaseTest {     @BeforeClass     public static void setUpBaseClass() {         //Do the necessary setup here     } } 

This method will run before any @BeforeClass annotated method in the subclasses: Source. Ensure that this method name is not used in any subclass to prevent shadowing.

If you need to run this just once (eg, if you are creating/initializing a large resource for all tests to use), set a flag in the super class to check whether the method ran or not.

This design will also ensure that if you change the test runner, you need not change anything else.

like image 172
Anubhav Avatar answered Sep 28 '22 10:09

Anubhav


Use @Before for setUp() and @After for tearDown methods.

EDIT: after some tests here I found that @Before and @After does not work for Test Suite. In your case you should use @BeforeClass and a static method to encapsulate your initialization code.

@RunWith(Suite.class) @SuiteClasses( { ContactTest.class }) public class AllTests {      @BeforeClass     public static void init() {         System.out.println("Before all");     }  } 
like image 31
nandokakimoto Avatar answered Sep 28 '22 08:09

nandokakimoto