There is no default provisioning in JUnit to do this the way you want. By using MethodSorters.NAME_ASCENDING you can ensure order by naming tests in alphabetical order as showed in other answer. Alternatively, you can create your own OrderedRunner and an annotation to fix this type of ordering.
public class OrderedRunner extends BlockJUnit4ClassRunner
{
public OrderedRunner(Class klass) throws InitializationError
{
super(klass);
}
@
Override
protected List computeTestMethods()
{
List list = super.computeTestMethods();
List copy = new ArrayList(list);
Collections.sort(copy, new Comparator()
{
public int compare(FrameworkMethod o1, FrameworkMethod o2)
{
SeleniumMethodOrder order1 = o1.getMethod()
.getAnnotation(SeleniumMethodOrder.class);
SeleniumMethodOrder order2 = o2.getMethod()
.getAnnotation(SeleniumMethodOrder.class);
if(order1.order() == order2.order())
{
return 0;
}
else if(order1.order() > order2.order())
{
return 1;
}
else
{
return -1;
}
}
});
return copy;
}
}
This makes use of an annotation that is created as below
@java.lang.annotation.Target(value = {java.lang.annotation.ElementType.METHOD})
@ java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
public@ interface SeleniumMethodOrder
{
public abstract int order() default 1;
}
Now you can write tests as shown below and provide order for them...
@RunWith(OrderedRunner.class)
public class StorageServiceWdTest extends WebDriverTestBase {
@Test
@SeleniumMethodOrder(order = 1)
public void testDeleteFile() {
logger.info("adding file");
}
@Test
@SeleniumMethodOrder(order = 2)
public void testAddFile() {
logger.info("adding file");
}
@Test
@SeleniumMethodOrder(order = 3)
public void testMoveFile() {
logger.info("moving file");
}
}
This will ensure that the tests will always run the given order parameter of SeleniumMethodOrder annotation.
Source: http://neopatel.blogspot.in/2013/06/junit4-custom-method-order-or-custom.html