How to run test methods in specific order in JUnit4?
I want to execute test methods which are annotated by @Test
in specific order.
For example:
public class MyTest {
@Test public void test1(){}
@Test public void test2(){}
}
I want to ensure to run test1()
before test2()
each time I run MyTest
, but I couldn't find annotation like @Test(order=xx)
.
I think it's quite important feature for JUnit, if author of JUnit doesn't want the order feature , why?
I think it's quite important feature for JUnit, if author of JUnit doesn't want the order feature, why?
I'm not sure there is a clean way to do this with JUnit, to my knowledge JUnit assumes that all tests can be performed in an arbitrary order. From the FAQ:
How do I use a test fixture?
(...) The ordering of test-method invocations is not guaranteed , so testOneItemCollection() might be executed before testEmptyCollection(). (...)
Why is it so? Well, I believe that making tests order dependent is a practice that the authors don't want to promote. Tests should be independent, they shouldn't be coupled and violating this will make things harder to maintain, will break the ability to run tests individually (obviously), etc.
That being said, if you really want to go in this direction, consider using TestNG since it supports running tests methods in any arbitrary order natively (and things like specifying that methods depends on groups of methods). Cedric Beust explains how to do this in order of execution of tests in testng.
Junit 4.11 comes with @FixMethodOrder
annotation. Instead of using custom solutions just upgrade your junit version and annotate test class with FixMethodOrder(MethodSorters.NAME_ASCENDING)
. Check the release notes for the details.
Here is a sample:
import org.junit.runners.MethodSorters;
import org.junit.FixMethodOrder;
import org.junit.Test;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SampleTest {
@Test
public void firstTest() {
System.out.println("first");
}
@Test
public void secondTest() {
System.out.println("second");
}
}
如果您摆脱了您现有的Junit实例,并且在构建路径中下载JUnit 4.11或更高版本,则以下代码将按其名称顺序执行测试方法,并按升序排序:
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SampleTest {
@Test
public void testAcreate() {
System.out.println("first");
}
@Test
public void testBupdate() {
System.out.println("second");
}
@Test
public void testCdelete() {
System.out.println("third");
}
}
链接地址: http://www.djcxy.com/p/61748.html
上一篇: GAE(和WTForms)的HTTP帖子