我们如何在Unit Testcase中编写两个@beforeTest方法?
我的测试用例中有两种方法。我想为每一种测试方法使用两种不同的 @BeforeTest
或 @BeforeMethod
方法。
我在单元测试类中编写了两个 @BeforeMethod 方法,但这两个方法都会在每个单元测试方法执行时执行。
那么我们如何声明@BeforeMethod 方法来单独执行特定的测试方法呢?
我的单元测试类如下所示:
public class MyUnitTest{
String userName = null;
String password = null;
// Method 1
@Parameters({"userName"})
@BeforeMethod
public void beforeMethod1(String userName){
userName = userName;
}
@Parameters({"userName"})
@Test
public void unitTest1(String userNameTest){
System.out.println("userName ="+userName);
}
// Method 2
@Parameters({"userName","password"})
@BeforeMethod
public void beforeMethod2(String userName,String password){
this.userName = userName;
this.password = password;
}
@Parameters({"userName","password"})
@Test
public void unitTest2(String userNameTest,String passwordTest){
System.out.println("userName ="+this.userName+" \t Password ="+this.password);
}
}
有没有办法使:
beforeMethod1
方法仅针对unitTest1()
方法执行?beforeMethod2
方法仅针对unitTest2()
方法执行?
I have two methods in my test case. I want to use two different @BeforeTest
or @BeforeMethod
methods for each one of my Test methods.
I wrote two @BeforeMethod
methods in my unit test class, but both methods are executed for every Unit Test method execution.
So how can we declare the @BeforeMethod
methods to execute for specific test methods individually?
My Unit Test Class look like:
public class MyUnitTest{
String userName = null;
String password = null;
// Method 1
@Parameters({"userName"})
@BeforeMethod
public void beforeMethod1(String userName){
userName = userName;
}
@Parameters({"userName"})
@Test
public void unitTest1(String userNameTest){
System.out.println("userName ="+userName);
}
// Method 2
@Parameters({"userName","password"})
@BeforeMethod
public void beforeMethod2(String userName,String password){
this.userName = userName;
this.password = password;
}
@Parameters({"userName","password"})
@Test
public void unitTest2(String userNameTest,String passwordTest){
System.out.println("userName ="+this.userName+" \t Password ="+this.password);
}
}
Is there a way to make:
beforeMethod1
method only execute forunitTest1()
method?beforeMethod2
method only execute forunitTest2()
method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有几个选项:
您可以使用 Method 参数声明 @BeforeMethod,检查该方法的名称,如果是 unitTest1,则调用 beforeMethod1(),如果是 unitTest2,则调用 beforeMethod2()。这可能不是我的第一选择,因为如果更改方法的名称,它会有点脆弱。
将这些方法及其 before 方法放在单独的类中,可能共享一个公共超类。
You have a couple of options:
You can declare the @BeforeMethod with a Method parameter, check the name of that method and if it's unitTest1, invoke beforeMethod1() and if it's unitTest2, invoke beforeMethod2(). This would probably not be my first choice since it's a bit fragile if you change the names of your methods.
Put these methods and their before method in separate classes, possibly sharing a common superclass.