Reputation: 8346
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 for unitTest1()
method?beforeMethod2
method only execute for unitTest2()
method?Upvotes: 1
Views: 1311
Reputation: 15608
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.
Upvotes: 3