163. Only one test should be written inside a single test method






1. Before going forward, lets once again view the code we have written in our previous post below: (i.e. The code with more than one tests inside a single test method)




2. As its not a good idea to write more than one tests inside a single test method, lets Refactor the Selenium Automation code by writing all the 3 tests into a separate test methods as shown below:



3. Save and Run the 'Class79.java' file by selecting the 'JUnit Test' option 
4. In this case, Observe that the Firefox Browser has launched and closed for 3 times instead of once,  for running the above three tests as shown in the below video.

Watch the Below Video:

Click Here to watch the video.

Download This Project:

Click here to download this project and import into Eclipse IDE  on your machine.

Why did the firefox launched and closed separately for each test method in the code ?

As we've three tests and we've written test method for each of our tests, hence we got 3 test methods in the Selenium Automation code. But in this case 'chapter1' page is common for 3 of the tests and hence its not required to close the application and launch it for performing the remaining tests. This has happened because of @BeforeMethod and @AfterMethod TestNG annotations.

The code inside the @BeforeMethod and @AfterMethod annotations will be executed once for each test method in our Selenium Automation code. Since we've three test methods in our code,  the methods under the @BeforeMethod and @AfterMethod annotations got executed thrice (i.e. once for each test method).

How to resolve this problem ?

Suppose if we want to run the methods under the @BeforeMethod and @AfterMethod annotations only once, we've to replace these annotations with @BeforeClass and @AfterClass. (i.e. The method under @BeforeClass will be executed before executing all the test methods inside the class and The method under @AfterClass will be executed after executing all the test methods inside the class.

So to conclude the executing process will be as shown in the below screenshots:

@BeforeMethod and @AfterMethod:




@BeforeClass and @AfterClass:



So lets implement the @BeforeClass and @AfterClass TestNG Annotations in the next post.


Please comment below to feedback or ask questions.

Using @BeforeClass and @AfterClass TestNG Annotations will be explained in the next post.


Followers

Labels