Home » Java » java – invoking a test method each time before other test methods-Exceptionshub

java – invoking a test method each time before other test methods-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a test method as below that two other test methods are dependent to this method and this method should run before these two each time and not only once for both.

 @Test(dataProvider = "requestParameterProvider", groups = "jsonRequest")
 public void saveNewActivity_correctValues(Service service, 
 Map<String, Object> requestMap){}

 @Test(dependsOnMethods = "saveNewActivity_trackRequest_correctValues", dataProvider = "responseParameterProvider")
public void commitActivity_correctValues(Service service){}

@Test(dependsOnMethods = "saveNewActivity_trackRequest_correctValues", dataProvider = "exceptionParameterProvider")
public void failActivity_correctValues(Service service, FailureReason failureReason){}

what happens at above case is saveNewActivity_correctValues method run once first and then two other method run after that. but i want first method to be invoked two times before each dependent method and once as separate test. i can’t put first method as @BeforeMethod because it is already a test and have a provider of it’s own.

How to&Answers:

Use the @Before annotation on the method you want to run before all tests.

If you don’t want it to run before all methods, but only some, either refactor your tests out into 2 classes and use @Before in one, and not in the other and move your methods appropriately.

The other option is to just call the method(s) from each test you want them to run before.

I’m assuming you are using JUnit – so see here:

http://junit.sourceforge.net/javadoc/org/junit/Before.html

If not, update your post with what you are using.