I am having a test suite which is having the following structure
TestClass1
- testmethod1()
- testmethod2()
- testmethod3()
- testmethod4()
TestClass2
- testmethod11()
- testmethod22()
- testmethod33()
- testmethod44()
In the above structure i want to execute the testmethod4() as the final one. ie) executed at last. There is a annotation @FixMethodOrder which executes a method in order not the testclass. Is there any mechanism to maintain order in test class and testmethod together. With the @FixMethodOrder i can execute the method by renaming the name of the test method but i can't instruct junit to execute the test class as the final one(last one).
By default, JUnit runs tests using a deterministic but unpredictable order (MethodSorters. DEFAULT). In most cases, that behavior is perfectly fine and acceptable. But there are cases when we need to enforce a specific ordering.
@Before and @After. @Before annotated method will run before each test method in the class. For example, if you have 3 test annotated method, @Before method will run 3 times before each @Test annotated method. On the other hand, @After annotated method will run after each test method in the class.
Annotation Type FixMethodOrder. This class allows the user to choose the order of execution of the methods within a test class.
Though quoting @Andy again -
You shouldn't care about test ordering. If it's important, you've got interdependencies between tests, so you're testing behaviour + interdependencies, not simply behaviour. Your tests should work identically when executed in any order.
But if the need be to do so, you can try out Suite
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestClass2.class,
TestClass1.class
})
public class JunitSuiteTest {
}
where you can either specify
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestClass1 {
@AfterClass
public void testMethod4() {
and then take care to name your method testMethod4
as such to be executed at the end OR you can also use @AfterClass
which could soon be replaced by @AfterAll
in Junit5.
Do take a look at Controlling the Order of the JUnit test by Alan Harder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With