I would like to know if there is a way to execute some method after executing my tests.
I am using eclipse and i would like to be able to run some or all of my tests and then execute some code,
so that junit will always execute my tear down once, always after the last test.
The concrete problem is that I am using selenium webdriver and i would like to execute webdriver’s quit method after all my tests are done. First I had static class managing webdriver reference, now i moved to singleton pattern. I believe there could be better solution, but right now I don’t want to use any IoC containers since I am java beginner.
So far i tried few approaches but none was successful.
Suit approach only works when i execute all my test:
@RunWith(Suite.class)
@SuiteClasses({SomeTest.class, OtherTest.class, AnotherTest.class})
public class TestSuit {
@BeforeClass
public static void setUp() {
System.out.println("setting up");
}
@AfterClass
public static void tearDown() {
System.out.println("tearing down");
}
}
but what if i would like to run just one test class or all tests from one specific namespace?
After class approach works only if all my test are grouped in one class.
I believe that NUnit has implemented SetUpFixtureAttribute , which is doing what i would like to gain, is there any counterpart in jUnit?
Have you considered using TestNG instead? You can use the @BeforeTest/@AfterTest or @BeforeSuite/@AfterSuite to run your browser open/close methods before/after a group of tests or suite of tests. (http://testng.org/doc/documentation-main.html)
< suite>< test>< classes>…< /classes>< /test>… < /suite>
Personally, I use the @BeforeMethod/@AfterMethod to load and close my browser, so I get a clean browser instance before each new tests. It takes longer of course to do this, but it’s just a choice that I made based on the kind of tests/software I’m running. This also allows me to run my tests in parallel threads, without having to worry about the grouping of tests in my test classes if I were to use @BeforeClass/@Afterclass.