如何与Junit一起按顺序运行测试方法 [英] How to run test methods in order with Junit
问题描述
我正在使用JUnit和Selenium Webdriver.我想按照我在代码中的编写方式来运行测试方法,如下所示:
I am using JUnit and Selenium Webdriver. I want to run my test methods in order as how I write them in my code, as below:
@Test
public void registerUserTest(){
// code
}
@Test
public void welcomeNewUserTest(){
// code
}
@Test
public void questionaireNewUserTest(){
// code
}
但是它不起作用,它总是按以下顺序执行我的测试方法:
But it doesn't work, it always executes my test methods in this order:
welcomeNewUserTest()
registerUserTest()
questionaireNewUserTest()
如果我用后缀Test命名我的方法,我会在某处读到答案,然后JUnit会按照我在代码中的排序方式依次执行它们.显然,这是行不通的.
I read an answer somewhere if I name my method with suffix Test, then JUnit would execute them in order as how I order them in code. Apparently, this doesn't work.
有帮助吗?谢谢
推荐答案
因此,对于此类测试(步骤彼此依赖),您应该真正将它们作为一个单元执行.您实际上应该在做类似的事情:
So for tests like these - where the steps are dependent on each other - you should really execute them as one unit. You should really be doing something like:
@Test
public void registerWelcomeAndQuestionnaireUserTest(){
// code
// Register
// Welcome
// Questionnaire
}
就像@耶利米在下面提到的那样,有几种独特的方法可以使单独的测试无法预测地执行.
As @Jeremiah mentions below, there are a handful of unique ways that separate tests can execute unpredictably.
现在我已经说过了,这是您的解决方案.
Now that I've said that, here's your solution.
如果您要进行单独的测试,则可以使用 @FixMethodOrder ,然后按NAME_ASCENDING
进行操作.这是我唯一知道的方法.
If you want separate tests, you can use @FixMethodOrder and then do it by NAME_ASCENDING
. This is the only way I know.
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestMethodOrder {
@Test
public void testA() {
System.out.println("first");
}
@Test
public void testC() {
System.out.println("third");
}
@Test
public void testB() {
System.out.println("second");
}
}
将执行:
testA(), testB(), testC()
在您的情况下:
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ThisTestsEverything{
@Test
public void T1_registerUser(){
// code
}
@Test
public void T2_welcomeNewUser(){
// code
}
@Test
public void T3_questionaireNewUser(){
// code
}
}
这篇关于如何与Junit一起按顺序运行测试方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!