Saturday, 11 August 2012

Junit Test Execution Continues

In my last junit post, i have written about some basic annotations of junit.This post is just an extension to the last post, today we will learn about @BeforeClass & @AfterClass.
 
@BeforeClass annotation is used to execute method which required run before class gets executed.


@AfterClass annotation is used to execute method which required run before class gets executed.

Now we already know from the last post that, @Test method is used to execute the test case method, it holds code of your test case. Think about a scenario, if you want to do login, logout once and then want to execute 10 test case method with the same login. This can not be possible with @before and @after method. But it is possible with the use of above two annotations. How?? Lets see how we can do that.

@beforeclass method will get executed once before all the test methods and @afterclass method will get executed after all the test method completed their run.

lets see some code for the above annotations.



Ok let's run this case, Oops... there is an error, isn't it? why is that error? Now when the annotations name is beforeclass that means it must be getting executed before the class itself gets instantiated. That is not fair :(. Before instantiating the class how we can call a method, think about the most used method of java application "public static void main()". Yes, you got it right now, you need to make @beforeclass and @afterclass methods static so that they can execute themselves before the class gets loaded.

Now change the code and run.

Output of the run-:
 

As you can see in the result, beforeclass & afterclass gets executed only once for all the test methods.

Now think and use this in your selenium/Webdriver automation scripts. I will be posting about the use of asserts in the test script in my next post.

Please feel free to drop a comment if you have any suggestion/comment/issue on the above post.

Thanks!! 
 
 

No comments:

Post a Comment

Related Posts

Related Posts...