Sunday, July 26, 2020

Part-6: Want to quickly become an Selenium Automation Engineer and build framework right from scratch?


TestNg Configuration and implementation

In Part-5, we modified our simple automation script into a real-time framework pattern wherein we have separate folders for test-cases and helper classes. We also added a few more functionalities to our intended test and executed it further. So now let’s introduce TestNG, the most awaited framework and we will learn the use of pending locators and other framework building stuff. I assure you by the end of this course, you will be able to develop a wide variety of tests.

 

TestNG is a unit testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use, in TestNG, refers to ‘Next Generation’, and it is perfectly equipped with next-generation functionalities, like annotation, report generation showing how many test-case passed or failed or skipped, control your test-cases like running only a few test-cases out of many, add priority to test-cases etc. So let’s not add more huge definition which will confuse more and directly work on it. You can find more on its official documentation.

Let’s install the TestNG plugin in our Elcipse. Open Eclipse, click Help->Install New Software


Enter the site URL as ‘https://dl.bintray.com/testng-team/testng-eclipse-release/’  in as mentioned below and hit enter, you should be able to see ‘TestNG’ as mentioned below:


Once you click on that checkbox, the ‘Next’ button will get enabled, click on it.



After clicking Finish, you might get below prompt, click ‘Install anyway’,


You can also check the progress of the installation.


Click ‘Restart now’. This will install TestNG Plugin in your Eclipse.


So just to check whether TestNG is installed, right-click your project and click ‘Properties’, you should be able to see ‘TestNG’


We will create a class which will house all our test-cases, lets name it as ‘TestClass’ under package ‘testSearch’, you know why we selected this package, because this is the package for test-cases.

As this is a TestNG based test-class, we will not use ‘public static void main(String[] args)’ for both compiling and running the class, but we will use TestNG for the same, we will see further how.


TestNg provides various helper annotations which prove very useful in test-case execution, rather team-up as an end-to-end solution for test-case execution driving. Below are some of the annotations:

No.

Tag Annotations

Comment

1.

@BeforeSuite

To be used when you have to load environment variables.

2.

@BeforeTest

To be used when annotated methods will be executed before each test section declared inside TestNG suite.

3.

@BeforeClass

@BeforeClass the annotated method is executed before any of the test methods of a test class.

4.

@BeforeMethod

@BeforeMethod annotated methods are executed before the execution of each test method for a particular class

5.

@AfterMethod

@AfterMethod annotated methods are executed after  the execution of each test method for a particular class

6.

@AfterClass

@AfterClass the annotated method is executed after the execution of every test methods of a test class.

7.

@AfterTest

@AfterTest the annotated method is executed after the execution of every test section declared inside a TestNG suite.

8.

@AfterSuite

To be used when you have to close/unload  environment variables.


Below are some of the helper attributes TestNG uses:

No.

Helper Attributes

Comment

1.

@Test(dependsOnMethods=(“A,B”)

This test-case will execute once A and B are executed.

2.

@Test(enable=false)

This will disable that particular test-case

3.

@Test(timeout=4000)

Used to increase the timeout of that particular test to 4 seconds before failing

4.

@Parameter(“{URL}”)

This is used to parameterize a test-case. Useful for that particular test only where it is mentioned. Here we mention the URL in testing.xml, eg: <parameter name=”URL” value=”www.abc.com”>

@Test

Public void getData(String str)

{

System.out.println(str);

}

5.

@DataProvider

Used to test a test-case with multiple data.

Eg:

@DataProvider

Public Object[][] getData()

{

Object[][] myObject = new Object[2][2];

myObject[0][0]=”email1”;

myObject[0][1]=”val1”;

myObject[1][0]=”email2”;

myObject[1][1]=”val2”;

}

 

@Test(dataProvider=”getData()”)


Don’t worry, we will cover all of the above with an explanation, while some are self-explanatory. 

So let's dive into our eclipse ‘TestClass’ that we created. To declare any test in TestNG we assign an annotation called ‘@Test’, this tells that this is a test method, and we write our test. For now, for better understanding we just convert our available test into TestNG, as below:

Here I am writing my first test, to initiate the browser, so creating a method browserInitiate(), we already required code from the previous example, so we will copy-paste that content from ‘FirstTest’ class. You can also see when we write ‘@Test’ it gave an error because it cannot recognize that tag, though your eclipse has TestNG plugin, but your project needs that TestNG dependency. 

As we are using Maven, we don’t need to do anything, just search that dependency using below:


Don't use any beta version, use a stable version:


Click on the link and copy the content:


And paste it in your pom.xml under <dependencies> tag and save the pom.xml and ‘TestClass’:


Now again go to the class where you are writing your test-case, ie., ‘TestClass’ and again hover over ‘@Test’, you will now find ‘TestNG’ a related suggestion which was not available earlier, so this came because you imported TestNG related dependency in your project


Click on it and the error is gone. Now if you right-click your TestClass->Run As, you will find ‘Run As TestNG test’ and not as ‘Java Application’:


You will find the same output as earlier, but here you will not write class for every test, but in the same class, you will write many tests and control them. Also, you if you see at the bottom in your eclipse console, you will find, it shows Status ‘PASSED’ for our test: ‘browserInitiate’, also it shows descriptive data of failures/skips, for which we have not written any code, but TestNG has provided that data.


Now as we need to plug-and-play with our tests, we need to have testng.xml file which is not available yet, so to get it right click your project-> TestNG->Convert to TestNG:


You will find below details, which are Suite Name, Test name, and class name in which you are doing below test. Click Finish[You can change the details as per your needs also]


Now in your package explorer, you will find testing.xml


Double click that file, click ‘source’ and verify the details that you entered:


Henceforth we will be using TestNG for our further part of our exciting test-case, we will use all the possible annotations in the same simple way, and I guarantee you that, you will master TestNG.

Don’t miss the next important article on TestNG annotation implementations and Cucumber available on Amazon Kindle

-Sanjay Nikalje



Sunday, July 19, 2020

Part-5: Want to quickly become an Selenium Automation Engineer and build framework right from scratch?



In Part-4 we saw a sample test-automation script which automated what we thought of automating as per Part-2, but it is a rough script which doesn’t hold any value as per industry standard because we are not following smartness, intelligence, framework. 

So in this part, we will modify the last script bit-by-bit and slowly convert it into a more optimized and smart code that follows a rule which every team member of your will follow[as the same rule will be laid for every member], let's jump into it.



As we saw above, when we search the word ‘selenium’, it does search it, but after it keeps the search text-box in dangling state. So let us relieve the text-box from this, as it is bad programming practice, once our work is done, we should make it a point, whatever we open we should close it as well.

So we will put our text-box into a WebElement and call the submit() method which acts as an enter key and removes the dangling state of the textfield, and update the last few lines of the code as below:

WebElement textField = driver.findElement(By.cssSelector("input.gLFyf.gsfi"));
textField.sendKeys("selenium");
textField.submit();

So now it will send the text as ‘selenium’ also and also search that text in Google by hitting enter[by using submit() method] as below:


Now we will add one more requirement, when I open the browser it should be in full screen and not part of a screen and also once the required work is done it should also close the browser[consider an example where you have 100 test, so it will keep 100 browsers open and reduce the performance of the system]. So we will just add two small steps as below:



First is ‘driver.manage().window().maximize();’ what this does is, it tells the chrome browser to manages its window to maximize it. So now when chrome browser is initialized before Google could open it maximizes it.

Second is ‘driver.close()’ , here it tells the chrome driver to close the browser of the current session and ‘driver.quit()’, here it tells chrome driver to close all of its open windows. You will understand it better when we have a child window open example further. So when we run above code it opens a browser, maximizes it, searches text ‘selenium’, hits enter, and closes the browser.

Give it a try!!

Now we will update our code in the form of methods, instead of all the code lying in a single class. Its always better to have methods calls to required methods of a class to fulfill its requirement rather than having all code bunch at one place, this what industry follows.

Maven has miraculously already helped you in creating two folder structures viz., 'src/test/java' and 'src/main/java', where 'src/test/java' is the folder where we write our test-cases and 'src/main/java' is the folder where we place our helper classes. So in order to create our test-case,  right-click on folder ‘testSearch’ under 'src/test/java' and create a new class ‘FirstTest’ in it. Hope you got why we created this class in 'testSearch' folder, the simple answer is all test-cases related stuff will lie under this directory only!! So slowly you will envisage more live benefits of Maven further.




PS: in the above screenshot please check the box ‘public static void main(String[] args)', I missed to check it while taking the screenshot. It is required because our execution will start from this test case and earlier class will only act as a helper class and we will remove the ‘public static void main(String[] args)’ method from ‘InitialTest.java’ class.

Let’s start updating our code now to formulate into a step further, towards a formalized way of framework pattern. Go to class ‘InitialTest.java’ and add whatever code it had earlier in ‘public static void main(String[] args)' into a method called ‘InitializeDriver()’, then create one more method called ‘closeDriver()’ after this method and cut two lines ‘driver.close(); driver.quit();’ from it and put in ‘closeDriver()’ method, ie now your code will transit from:


To something like this:


So this ‘InitialTest.java’ class will become your helper class, to provide you with helping methods like browser initialization and closing the browser tasks. Now let’s move back to class ‘FirstTest.java’. 
You just need to add below three lines of code and run it:

InitialTest initial = new InitialTest();
initial.initializeDriver();
initial.closeDriver();

The first line, creates the object of the class InitialTest, second line using recently created object ‘initial’ calls the method ‘initializeDriver()’ present in that class to initialize the browser and the last line, as done earlier closes all the browsers opened by the driver.
Once done, right-click and as ‘Java Application’:


This will again give the same result as earlier, of opening the browser, searching closing the browser, but now it’s in more tuned and proper industry format.

In the next session, we will update this with the new paradigm of 'TestNG' and further important test-cases and learn further. Till this point, it was very important update our code from simple few lines to a certain standard industry accepts, here on we will write everything in TestNg and make our tests very powerful than earlier, where instead of running as ‘Java Application’ we will run it as TestNG test-case, which will also give us options to run few test-cases out of the whole, ordering test-cases etc..etc.

Thanks for reading and don’t miss the next part TestNG!!

~Sanjay Nikalje


Sunday, July 5, 2020

Love...across the Fence!!



Chapter-1

Mumbai, 31 December 2015, 1:30 am: After astonishing New Year party with Ashu and Pankaj, it was time to upload party pics with other friends on Facebook. ‘Wow, That’s nice’, ‘Cool Man’, ‘Nice pictures’, ‘Picture says all bro, Happy New Year!!’ etc etc. Got numerous messages like this from many of my friends. I started searching my friends New Year celebration pictures, all were cool. Their pictures stated their unique way of celebration and added more joy and colours to my happiness.

I scrolled and scrolled for another 30 minutes, my eyes iced on a profile... ‘Ruh Quershi’!! Wow, she looks so good. Entered her profile, Super.... just amazing. Closed Facebook after a while and went to sleep.

At 3:30 am, I again got up and logged-in Facebook, to check her profile again. No new updates, but  her picture seemed to get updated in my eyes, everytime I was looking at it. Now I checked everything that the profile had, down there I found that she is from Pak****n. Freezed and I moved behind.

Next full day I didn’t visit FB, but was feeling something throughout the day. At night I again checked her profile, but with every visit, I was feeling as if same photo was getting better and better. On 06 January I called up Anshu[Anand Shuke] and asked him to meet urgently at 5:00 pm at Sukandi Saloon[our free waiting and chatting area, where we discussed everything from Sarita to Babita, from Mava to Goa]. Anshu asked me ‘What happened Glen? Is everything fine?’ I told him, ‘Will talk once we meet’ and kept the phone. Probably citing the seriousness in voice he informed Pankaj as well.

‘So GD, what’s the matter? Who is the girl this time Mr. Majnu?’ Anshu broke the ice with these lines and started the conversation. ‘Hey,I am not kidding’ and they both started laughing, ‘Girl, I guessed it properly’ Anshu said and here they laugh again. Sukandi, said, ‘Gilen baba is lucky, everytime new girl and we are lucky everytime we hear a new story, and they all started laughing...’. ‘Today’s chai on whose diary?’ Sukandi asked. Anshu said ‘Of course Glen today.’ I got up for leaving the place and this made the atmosphere bit serious.

‘Ok, tell what is the issue?’ Pankaj asked. Guys, I want to discuss something very much serious. I iterated the whole Pak****n story in next few minutes. Pankaj said, ‘Just this much only right? Forget it, no crossing the fence bro. It would add more problems.’ ‘No, actually three days back I sent her a friends request and yesterday she accepted it, she pinged me on chat that, 'Mumbai is beautiful and she would like to visit Mumbai once’ I replied. Anshu said, ‘Sir, stop your boat here only, the water will become more deeper further, block her, forget her.’ As if I spoiled everybody’s mood, I cracked a Santa-Banta joke to get the choked mood back again to normal. While leaving, Pankaj kept hand on my shoulder and said ‘Stop it’ and went.

 

 Chapter-2                                                                 

9th May, Saturday and my birthday too. Once of the most surprising birthday, my father gifted me a brand-new ‘iPhone 5s’, my dream gadget. Can’t expect more happiness than this. Every year with my birthday starts our yearly challenge week also. We friends challenge each other a task, one who loses pays party bill and winner is given a ‘Mr. Unbeatable’ title and given a chance whether he wants to accept or reject a challenge next year, man with options. Last year I won a challenge of gulping down 21 Jhama gulab-jamun in just 7 minutes. But this year I opted to accept a challenge.

 Anshu brought a Bajaj Chetak scooter and put it on middle stand and said this is your challenge. I thought I have to lift it, fear of losing, melted my masculine power. I went near it and started lifting it....’Wait boss..... What are you doing’ Anshu said. I asked him ‘I have to lift it for how much time?’ ‘No that would be too easy, the challenge is to drive this darling from here to M.G. Road and get it back and put on main stand back without stopping.’ Anshu knew I know how to drive a scooter, still he is giving me this challenge, Stupid nut...I smiled and felt good about accepting the challenge.

First I respected the scooter, by tilting it to 30 degrees when on main stand. This invention of starting any type of scooter in this unique manner goes to Indians only. I have even seen Suri uncle doing this to his scooter, who works for Bajaj Automobiles. Respect ceremony is over, I sat on the scooter and gave it a faadu-kick. ‘Ghur-ghur.....ghur-ghur...ghrrrr’ here it starts, and I am all set to complete my challenge. I asked Anshu to be pillion-rider, he said ‘No Thanks....Best of Luck’. I put first gear, little accelerator, and here I go. After taking a small right turn in few meters I put the second gear and after putting it, I realized the clutch wire is broken, hand-brakes are not working properly, Which means, if apply leg break without clutch the scooter will stop, I might lose challenge and I don’t know whether it will start again, or is there enough petrol in it or not. Now without brake can’t accelerate also on this busy street, so tried honking, the horn sound was so low, as if a dying person is asking for water. Ohh God, I understood Anshu’s challenge now, he gave me an about to die beast in my hand. Somehow as my destination arrived, I kept a huge winners smile on my face, somehow stopped the vehicle in front Pankaj and Anshu. Anshu seemed surprised seeing me back alive with all my bones intact. As soon as I parked the vehicle on center stand, the spring of the stand came off, but ‘Bajaj bharose ki gaadi’ kept my pride intact and remained on center stand without it.

 Now it was my turn to challenge. ‘Eating 2 eggs in 5 minutes’ I said. Pankaj gave a thudding smile and said, ‘Learn how to challenge Sir... I accept it’. I said ok, today afternoon 1:00 pm we are going to Pune. ‘Pankaj and Anshu seemed baffled, ‘Pune? Why Mumbai hens are on strike, they are not giving eggs’ Pankaj said and they both started laughing. ‘No, but I will give my birthday party also over there and one who loses pays the party bill as well’ I replied.

Pankaj got his father’s antique Yezdi, I got my 350cc Bullet Machismo, Anshul gave company to me as a pillion-rider. At 5:30 pm we reached ‘Toni-Daa-Dhaba’ situated on old Mumbai-Pune Road, near Talegaon Pune. They both were still in confusion why they came so long just to eat eggs. Anshul said, ‘No doubt place is fantastic, but you could have given party in Mumbai as well, we need to return back also’ anguish Anshul replied, who’s back was still aching being a pillion-rider for 3 hours.

The waiter came for the order, the first thing to have in ‘Toni-Daa-Dhaba’ is the mouth-watering Lassi. I ordered 3 Lassi for three of us, the taste I tell you. And then was the time for challenge, ‘So ready juvenile?’ I asked Pankaj. The word juvenile probably hit him badly and loudly he said ‘Yes, get it’.  I took the waiter to a distance and gave the order. It’s been 45 minutes, the eggs have not arrived yet, Pankaj said, ‘Pune people read mantra’s in hens ear then the hen gives egg I guess, that’s why it is taking time..’ and they both smiled. Pankaj’s happiness couldn’t survive for long as the order came, ‘What is this? Are these elephant’s egg’s? This is cheating... these are not eggs’, Pankaj started crying looking at the eggs size. ‘Emu, these are Emu eggs’, I replied. Both myself and Anshu started laughing at Pankaj facial reaction. Out of the five minutes Pankaj spent 2 minutes in looking at the eggs and where to start journey query. Well he couldn’t finish it, so we two joined him in finishing the eggs with salt, pepper, some green and red chutney. Delicious!!

It was 7:00 pm now, we paid the bill and got up to return to Mumbai and it started raining. Seasons first rain, smell of the soil, wow. But soon we realized we could not return that day, as due to first rain, vehicles skid on road and it is dangerous travelling. We enquired for some staying place, the waiter suggested ‘White House Hotel’, well it wasn’t that costly for a night’s stay, we updated our parents about our current scenario and went to the hotel, which was near-by.

I was unable to sleep, and also there was free wifi[due to free wifi, I was unable to sleep], so thought of using it via my new iPhone and checking who all wished me on my birthday. I logged-in to FB and found that out of many wishes there was one from ‘Ruh’. ‘Happy birthday Glen!!’ She still remembers me, I was happy to receive birthday wishes from her and fearful too because it came from Pak****n. Somehow I couldn’t control myself, found her online, ‘How are you?’ I asked Ruh.

 Continued in next release....

~Sanjay Nikalje



Friday, July 3, 2020

Part-4: Want to quickly become an Selenium Automation Engineer and build framework right from scratch?


Selenium WebDriver, Locators...

In Part-3 we built a project using Maven, which created a wonderful project structure, if you see properly it has ‘src/test/java’ and ‘/src/main/java’ folders. We will normally use ‘src/test/java’ to write our test-cases inside it and ‘src/main/java’ to write the miscellaneous/helper classes[we will discuss this further].

So for now, we start our first automation script and we will keep on enhancing it further.  Go to your eclipse IDE to ‘GoogleSearchTest’ project that we created in Part-3. Right-click on ‘src/main/java’ >New-Class->IntialTest[Give this as the class name]



Once you click ‘Finish’ a template of your class will be formed. Paste below lines  as mentioned in the screenshot:

System.setProperty("webdriver.chrome.driver","path to chromedriver.exe");

Webdriver driver = new ChromeDriver();


Now go to the link https://chromedriver.chromium.org/downloads and click ‘ChromeDriver 83.0.4103.39’, because this is my current Chrome browser version.




Now select what OS version you have. Since I have Windows machine, I will click the appropriate one  as below, to download it to my drive:




Now go to the location where it is downloaded and move it any location of your choice[if required] and unzip it, to get the .exe file. Copy the location where it is unzipped, for me, it is ‘C:\Software\drivers\chromedriver_win32 (1)’: 


Now update this path in your code as below:


You must be still wondering, why there is still an error even after so many steps. These are repeatable steps, occurring in almost every scripts, so now after gaining the understanding of these steps, you won't find it lengthy at all. 

Secondly, there is one more magic Maven which we will see, is that now, for the above error line we don't need to download Selenium jar, but instead of we doing it,  we will ask our friend Maven to do it for us, how? Just type ‘selenium maven dependency’ in google, and now navigate to the link suggested and click on ‘Selenium Server’ link:


And select the latest stable version, never select ‘Alpha version’ as below:


Now just click/select the text available inside the box:


Go to your eclipse>double-click pom.xml file[it’s the heart of your project] :


Copy text after  ‘dependency’ tag as mentioned below and save it:


Now go to your code and hover on the first error, you will find some solutions now to resolve your issue, which was not present earlier:


One issue resolved:

Now again hover mouse on another issue, it will suggest corrective measures to be taken and select the option mentioned below:



The code now after resolving the issues, is free from errors, because Maven provided all the corrective implementations that the code needed, without you doing anything, other than just hovering and selecting appropriate suggestions:



What do the above two lines do?:

System.setProperty("webdriver.chrome.driver","path to chromedriver.exe");
-This basically sets the system property to key named ‘webdriver.chrome.driver’ and value is the path  where the chrome driver is downloaded on your system.

Webdriver driver = new ChromeDriver();
-This is basically used to create an instance of the chrome driver.
Now you have the power of  chrome-based driver with you and you are all set to do whatever actions you want your chrome browser to do. 

Remember our test-case was to open Chrome browser, then open Google.com and then type the word ‘selenium’ in Google search box, it should display various options Google provides as per its search criteria. So now add ‘driver.get("http://www.google.com");‘ line in above code > save > right-click > Run As > Java Application:



Magic: The moment you run this, another chrome browser instance will open and it will run your desired test-case



There are 2-3 points by which you can guarantee that the browser opened was as an output of an automated test-case:
  1. In your eclipse IDE console, it will show message: ‘ChromeDriver was started successfully.
  2.  On newly opened browser it will show message ‘Chrome is being controlled by an automated test software’
  3. And the third is the desired URL being opened.


Yes, this confirms you have successfully automated a simple browser-related test-case. Congratulations!!

Now, let's move to locators. Selenium has the following locators:


But what are locators?

Selenium provides a number of Locators to locate a GUI element precisely on a web-page, whether its a text-box, radio button, or any other element. So using these locators we can find the web-element and do our required set of actions on it. We will see it’s usage in due course. Simple, right!!

So now for our test-case, we need to send a string/set of characters called ‘selenium’ in Google search box. So to find locator for this, right-click the element on which you want to perform the action, in our case, right-click inside the search box.


And select ‘Inspect’, you will see below[highlighting the part of the code on which we inspected]:


Here we can see inside the highlighted portion a tag starting from ‘input’ having various attributes and associated values for it, like attribute ‘class’ has value ‘gLFyf gsfi’ and many others following it. We will use ‘CSS selector locator to uniquely identify our element and how to implement it is, given in below code:
driver.findElement(By.cssSelector("input.gLFyf.gsfi")).sendKeys("selenium");

You can use below cheat-sheet for finding elements using CSS:

No.
Tag
Comment
1.
tagname[attribute=’value’]
To be used when you have tagname, attribute and value
2.
[attribute=’value’]
Above can also be written like this, excluding tagname
3.
tagname[attribute*=’value’]
To be used when using a regular expression, in case the value is too big, you can use part of it.
4.
tagname#idValue
To be used when you have ‘id’ attribute and value, a shortcut
5.
tagname.classValue
To be used when having ‘class’ attribute and value, a shortcut

So in our example, we used tagname.classValue like ‘input.gLFyf.gsfi’ , ie tagname is ‘input’ and attribute ‘class’ has value ‘gLFyf gsfi’. The small catch here is if you see properly in our eclipse code we have mentioned class value as ‘gLFyf.gsfi’ and on Google inspect page, it is ‘gLFyf gsfi’.

So whenever using class as an attribute and if the value of the class has space we need to replace that space with a dot(.). As we have successfully found the element, we need to send out characters or string ‘selenium’ into it. We do that by writing ‘.sendKeys(“selenium”), to the element we accurately found.

Now again run the code as ‘Java Application’ as mentioned earlier:




Now you will find below:

Wooo... You have successfully automated your required manual test-case as mentioned in Part-2.

Isn’t it easy, as I told you earlier? Do comment and let me know your feedback, if this was helpful to you or you would like to refer this to your friend or colleague who wants to learn automation.

In the next section Part-5, we will improvise this further and use all the locators and other things like TestNG, Screenshot, Logs, ExtentReporting, Jenkins and many-many other automation features to build a robust framework.



How to create any mathematics tables with excel...

  Generate any tables with excel... 1.        Go to excel sheet, in first cell ‘A1’ enter the number whose table you want to generate, for...