The JUnit Touch

In this post we will focus on using a unit testing framework called JUnit which helps to organise and execute our test code efficiently.

WHAT IS JUNIT?

JUnit is a Java-based, open-source framework to help you execute unit testing. JUnit is mostly used to test unit or components of your application like classes and methods. JUnit also helps to run automated tests be it API or UI.

This post will help you use JUnit annotations in your Selenium framework. We would be looking at examples of JUnit annotations are that are used for a specific purpose in Selenium.

WHAT ARE JUNIT ANNOTATIONS?

JUnit annotations are meta-tags that provide data about the test methods and test classes outlined in our code structure. In order for our Selenium framework to execute in the most efficient manner we should add JUnit annotations in our script.

Below is the list of every JUnit annotation in Selenium that will be covered in this blog

@BeforeClass

@Before

@Test

@After

@AfterClass

@Ignore

*Note* – For our framework we shall be using JUnit 4.

In order to get started with JUnit 4 we need to add the dependency to our pom.xml as in the example below.

@BEFORECLASS

The @BeforeClass annotation is used to initialise objects that that could be used in our tests. When we use an object in the BeforeClass method, it would be invoked only once. The main usage of @BeforeClass annotation is used to execute code before all the tests listed in the test cases are executed.

In our example we are going to remove our public static void main method for the script. We will wrap the code for setting the property of the Chrome Driver inside of our @BeforeClass annotation. I will also add that we must make the method for using the @BeforeClass annotation static in order to use it. I will also print to the terminal window a simple statement to show the order of the test execution. This is done via the system.out.println() method.

@BEFORE

The @Before annotation is used when we want to initialise an object or perform an action for the duration of the test method . In our framework we are going to duplicate our tests 3 times to demonstrate the usage of @Before. As a result of having 3 test methods the @Before method will be called a total of 3 times, once for each test method.

What we shall do is to move the line of code relating to creating the driver object and maximising the browser window in the @Before annotation as for each test run we would like to ensure the browser is at its maximum screen size.

@TEST

The @Test annotation informs JUnit that the method that is tagged against can be run as a test A single test class may comprise numerous test methods in it tagged with @Test.

In our example we are going to duplicate the test using the nomenclature _capital letter to ensure the tests run in order for the purpose of our demo.

*Note* JUnit has the ability to add test script execution ordering. We shall explore this in later posts.

@AFTERTEST

The @After annotation is used to tear down pervious actions that we would have used in previous test setups i.e. the @Before method .Tear down methods can be used to erase the state of a pervious test environment.

In our example we are going to close down the browser after each test run using the close() method.

@AFTERCLASS

Our @AfterClass annotation method, is executed once. It will be executed after all tests have completed. The @AfterClass tag is used to clean up operations that we would have started in our @BeforeClass method.

In our example we shall use the quit() method of Selenium to shut down all Chrome Driver system processes.

*Note* The @AfterClass annotation should use a public static method in order to be used.

@IGNORE

The @Ignore annotation tells JUnit that the associated method to not be executed. In cases where we do not want to execute our methods we can temporarily place that block of code with the @Ignore annotation to avoid test case execution.

In our example we shall duplicate a 4th test case and tag it with @Ignore.

Now we shall execute the tests . On the BasicTest class file right click and select Run BasicTest.

Note in the terminal window we shall see all of our methods run in the following order.

From the test run we can clearly see the following JUnit execution runs:

@BeforeClass ran once.

@AfterClass ran once.

@Test ran 3 times

@Ignore has ignored the 4th test.

We can also observe how clean and concise our test class now looks with the use of JUnit.

Advertisement

A Basic Test Script In Java

We pick up right where we left off which is now to incorporate our first basic Selenium test script. This script will be a very simple script that will open a webpage. As we get further on into developing our tests, we will adopt best practices such as using an execution framework (J-Unit) assertions libraries (HamCrest) with the addition of using the modelling technique (Page Object Modelling) this will incorporate typically good programming practices such as DRY and SOLID.

In future blog posts we will also start to perform actions on the website, then put together an end to end framework. Let’s open our IDE IntelliJ and click on new project you should see the following window screen displaying below.

Ensure to select Maven as the option and click on the next button. There will be a further screen which will allow us to enter our project name. I’m going to call this project automationodyssey. You are free to call the project a meaningful name.

Once done click on the finish button you will see a project screen that will have the following folder structure .idea, src \main\java, src\main\resources, src\test\java. This is a typical Maven folder structure, this has been created for us by Maven. I will be going into further detail about Maven in a future blog post.

In order for us to start using Selenium we need to add Selenium-Java as a dependency to our project. Adding a dependency allows us to use Selenium-Java library. We do this by adding the Selenium XML to the pom.xml file. The pom.xml file will handle all other project dependencies we may need in future.

Handling our dependencies in this manner allows us to update versions and fixes to dependencies should they require change. When I first started out in test automation I downloaded .jar files and added these to the external libs folder.

This became an inefficient way as you downloaded a new .jar file for every version update, then delete your old .jar file. Rather now the site https://mvnrepository.com/ hosts the files and XML codings, it’s a small matter of making the changes direct to the pom.xml file and updating information such as the version number.

In the pom.xml file place the following line of code under the version tag as show below.

<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
</dependencies>

Now under the src\test\java folder right click under the new option select add Java class and name that class as BasicTest. A Java class is where we write and house our code. Typically in a Java class we house things such as fields, constructors, methods and nested classes. As we progress with our tests we will see these building blocks being housed in our Java classes.

Now in the Java file we are going to create our first field which will be the WebDriver field and assign it to a variable called ‘driver’ as shown below. *Note* if you see the class name WebDriver highlighted in red this is a warning to us to import the WebDriver class into our project file.

You can fix this issue simply by right clicking on the project name then in the Maven option reimporting the project. You will then need to head back over to the Java file and under the field placing the cursor over the declared WebDriver field and selecting the class to import as shown below.

In Java we need explicitly state the entry point for our program.We do this by adding the following line of code to our Java class file, public static void main (String [] args) { } . I won’t go into detail regarding that line of code, we can further explore this in another post. Inside of the curly braces of public static void main (String [] args) { } add the following lines of code as below.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class BasicTest {

   static WebDriver driver;

   public static void main (String[] args){
     
System.setProperty("webdriver.chrome.driver","src/main/resources/chrome-driver");
      driver = new ChromeDriver();
      driver.manage().window().maximize();
      driver.navigate().to("https://the-internet.herokuapp.com/login");
   }


}

Looking at the lines of code what we have done is to set the system property this allows Selenium to use ChromeDriver a standalone server which will let our code run against a Chrome browser. I will also add the ChromeDriver standalone server in the resources folder you will need to add the Chrome.exe file.

This file can be downloaded at the following site https://chromedriver.chromium.org/home. Ensure that you are downloading the version that matches your current Chrome browser version. The version can be located under the Chrome about option.

Now in the test file right click and select Run BasicTest() main to see Selenium in action.

If you have followed all of the steps correctly you would have seen a browser spin up and the following page displayed below. Congratulations you have successfully ran your first Selenium test script!

In the next post will further build on interacting with the page and using the runner framework J-Unit. Unit then take care and thanks for reading this post.

Installation The Simple Way – Part 2

1_SXzqtB1jDTP46FJsPAnFew            download.png         zl48EuhC_400x400

We pick up were we left off with our installation guide. Next on the agenda will be to install Java, Maven and IntelliJ using Chocolatey.

Disclaimer – Please ensure that you gone through Installation The Simple Way first before continuing with this post.

First lets check that we do not have Java 8 installed (at the time of writing  JDK8 is the version of the Java environment being used for this post).

Open up the command line window in your Windows machine. You can simply enter the letters cmd in the search field located at the bottom left hand corner of the screen. Next on the screen enter the command “java -version”. Assuming that you have not had Java installed before the following message should appear in the command line window ‘java’ is not recognized as an internal or external command, operable program or batch file.

Screenshot 2020-07-28 at 18.39.45

Next we want to bring up a new PowerShell window. In the search field bar, type in PowerShell. Ensure that you are running the command line with admin rights.

In the window type in the following command  “choco  install  jdk8″. Chocolatey should now start to install the  JDK8 (Java Development Kit 8), more on the JDK in another post. Screenshot 2020-07-28 at 18.59.48

Now to ensure that we have successfully installed Java open a new command window and type the following command “java -version”.  You will be presented with the following text in the window “java version “1.8.0_211″ Java(TM) SE Runtime Environment (build 1.8.0_211-b12) Java HotSpot(TM) 64-Bit Server VM (build 25.211-b12, mixed mode)”

This would confirm that we have successfully installed java on our machine. Right one down ….two to go! Next up we shall install Maven our project dependency manager. First lets check that we do not have Maven installed, on the command line window enter the following command “mvn -version” if you do not have Maven installed you should be presented with the following text in the window “‘mvn’ is not recognized as an internal or external command, operable program or batch file.” 

Open the PowerShell window and type in the following command “choco install maven”. Remember to ensure the PowerShell is running as an admin. The window below should be displayed as Chocolatey installs Maven.

Screenshot 2020-07-28 at 20.05.36.png

 

We can see from the screenshot that Chocolatey successfully installed Maven. we can confirm this by heading over to a new command line window and typing the following command “mvn -version”. The following text should display “Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f) Maven home: C:\ProgramData\chocolatey\lib\maven\apache-maven-3.6.3\bin\.. Java version: 1.8.0_211, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk1.8.0_211\jre Default locale: en_GB, platform encoding: Cp1252 OS name: “windows 10”, version: “10.0”, arch: “amd64”, family: “windows”  “

Screenshot 2020-07-28 at 19.25.14.png

We now have to install Intellij IDE our development environment. You can check if you have this installed by trying to search for the software in the windows search bar. If you do not have it installed please follow the next steps.

In the command PowerShell window enter the following command “choco install intellijidea-community”.  We are installing the community edition of Intellij as its free! The following script should be running as below in the screenshot.

Screenshot 2020-07-28 at 19.45.43

Now lets check that Intellij is now installed on the search bar by typing in “Intellij IDEA Community Edition 2020.1.4”. The following search results should display as per the screenshot below.

Screenshot 2020-07-28 at 19.50.01.png

We are now set to create our first basic automation test script. See you in next post!

 

Installation The Simple Way

install.png

 

When starting out with test automation one of the first things that is required will be to install various software components. This software will allow for us to create some automated tests.

For our first setup will be using the Java implementation of the Selenium API. The main parts of software that will be required are as follows:

Java –  Java is a programming language and computing platform first released in 1995. There are lots of applications and websites that use Java.

Maven -Maven is a dependency management and  build automation tool used primarily for Java projects.

IntelliJ IDEIntelliJ is an Integrated Development Environment used for computer software development.This is tool in which developers and QA can write code.

The software components mentioned above will be main pieces that we shall be using to get started. As we progress with getting started with Selenium and Java their usages will become more apparent.

When it comes to installing Java and Maven on a Windows or Mac machine this can prove very tricky. In the past this would require changes to things like the system variables and add various changes to the paths in the system. This could easily lead to human error and cause  lots of setup issue. I have had first hand experience of this.

Fortunately for both Windows and Mac users there are package managers that can do all of the labour intensive work of downloading what we require and performing all of the setup tasks.

The two package managers that I have used are Chocolatey (Windows based) and Homebrew(Mac OS based).

choco.png

homebrew-social-card.png

I shall start off with how to install Chocolatey for Windows. Window typically tends to be the most widely used operating system for business and users. I will in future put up a post about getting started with Homebrew.

You first want to open up the Windows PowerShell command line (you can search for this in the windows search bar) please ensure you open this as the window administrator you may face installation privileges issues when we start installing the software components  we require. You should see the following window below:

Screenshot 2020-07-08 at 15.44.31

With PowerShell, you must ensure Get-ExecutionPolicy is not restricted as mentioned on the chocolatey website.

Run Get-ExecutionPolicy. If it returns Restricted, then run Set-ExecutionPolicy AllSigned or Set-ExecutionPolicy Bypass -Scope Process.

The the next thing you want to is to copy the below command in the PowerShell window:

Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1&#8217;))

The PowerShell screen should display as below. In the case of my setup I had to changed the execution policies as mentioned and this will be evident in the screenshot.

choco_install

Now if you don’t see any errors close down the PowerShell window reopen the window and type the following command ‘choco’ you should see the version number of Chocolatey and you have successfully installed Chocolatey on your Windows machine.

Screenshot 2020-07-08 at 16.15.03

In the next post we will be actually using Chocolatey to install Maven, Java and Intellij.

See you in the next post!

 

………….The Odyssey Is Back!

hiatusover

So…….Im back. It’s been a rough one year and nine months to be precise. Apologies to anyone who has been patiently waiting on my next article. I’ve had a lot of personal commitments that required a lot of my time, unfortunately life can get the better of us.

Also more recently we’ve been enduring a global pandemic, which I’m sure none of us saw coming. This has really changed the world and impacted each and everyone of us in varying ways.

However we should not lose hope and keep moving forward in these challenging times. I will now be more committed to bring  content to the blog around everything in the world of testing and test automation.

Watch this space in the coming days and weeks, stay safe!

Sanderson

Automation..The Pro’s..The Con’s

pros-and-cons.jpg

 

Test Automation has many advantages and disadvantages when applied to the STLC (Software Testing Life Cycle). In this post we will discuss a list of pro’s vs con’s so without  further ado here are my thoughts on the pro’s vs the cons with test automation.

Pro’s

Time Saving – When working in agile development environment repeated change is invertible, this will lead to regression testing having to be performed on numerous occasions based on changes made to the application. Having QA repeatedly run the same tests over and over again can often lead to human error.

In some cases (which I have seen) tests can be skipped out due to time constraints. With automation, tests can be run over night leaving QA the time to focus on exploratory testing and find unknown defects in the application.

Economical – A lot of test automation tools such as Selenium WebDriver, Appium, Rest Assured, Postman are open source tools. Meaning these do not cost your organisation anything to implement them as part the testing approach.

Once the automation test suites are correctly in place and you have a robust, maintainable, scalable and reusable test automation framework you will invertible require less resources running tests which will bring about a cost saving to the  organisation.

Speed – Automation tests can run at speeds that humans simply cannot keep pace with a single test case with multiple steps can run in milliseconds. This will produce faster feedback to the project team on the current status of the tests being ran and the state of the application.

Clarity – When it comes to running manual tests, a lot of the time its hard to get clarity on the overall picture of how many tests are currently being run, how many tests have passed and failed which areas of tests are currently being executed.  With automation this problem is easily solved if implemented correctly using a continuous integration tool like Jenkins, TeamCity or Travis CI. These tools providing great reporting mechanisms during and after test execution.

Con’s

Learning Curve – Using test automation tools in a proficient manner  for various types of tests such as Performance, API and UI test almost certainly will require a good core understand of programming languages i.e Java, design patterns i.e page object model and framework approaches i.e data driven framework. This can prove a steep learning curve for manual testers with a fear to move out their comfort zone.

The sliver bullet syndrome –  Test Automation is no replacement for manual testing. Test Automation is not considered by many top guru’s in the world of testing to be testing at all…gasp…. yeah I know right! Its checking by running predefined steps to result in an end goal. Current automation tools cannot think out of the box like a human can to determine varying paths to test a particular area in an application. This then limits the scope of how dynamic tests can actual be.

In the next post I will be diving into writing our first basic UI automation test script using Selenium WebDriver with Java.

So What Is Automation Testing..?

Screen Shot 2018-09-30 at 17.34.56

Automation testing is an approach were a skilled resource writes coded scripts by utilising various programming languages and software to automatically process tests    for the AUT (application under test). It replicates the manual process of testing without the need of actual manual  intervention.

Typical automation testing lends itself to regression, load and performance testing.      The main goal of automation testing is to increase the testing efficiency and ensure the quality of the software is at the high standards before release to the end-user.

Why Automate?     

 In today’s world business’s are coming up with constant improvements, enhancements to applications on a daily, weekly and monthly basis.With this in mind developers and QA engineers have their work cut out with ensuring the current system and new enhancements work as expected.

Imagine an update to the Amazon website were a user is able to buy an item now and pay for it later. The developer would have to implement this new feature and QA would have to ensure this feature works as expected with no deviation. On top of this QA would also need to ensure this change have not broken any parts of the existing system.

In my personal experience I have seen cases were changes similar to this could have around 20+ test cases just to check the feature works. However the regression suite of tests could be in excess of 1000 test cases! Yes I said 1000 test cases Amazon is a huge site.

Now imagine the team only has 3 QA resources to test 1020 tests in five days. That would mean each QA would have 340 tests to run in 5 days…meaning 68 tests per day. This would increase pressure on the QA team to deliver the completed suite of tests in the allotted time.

Due to the time constraints QA would probably not have enough time to conducted a personal favourite testing approach of mine “exploratory” testing. More on exploratory testing in another post. This is were automation testing comes into the mix.

Imagine those 1000 test cases some how could be automatically executed in less than 24hrs. How great would that be! Those 20+ tests would only require manual intervention. This would allow more time to explore the application as a whole to uncover defects that might have gone unnoticed.

The automation process would take care of the regression test execution then report back the results of the test run. This would give faster feedback as to the state of the AUT. Then the team can determine if the AUT is ready to be released in the wild.

In the next post I will be discussing the pro’s and the con’s of automation testing.