Software testing has emerged as one of the most promising careers in today’s world. The invention of many test automation tools have made testing easier but the presence of many tools creates a lot of confusion among the testers over the selection of the right tool. JUnit is one of the test automation tools and this part of our tutorial discusses JUnit.
Introduction to JUnit Framework
JUnit is an open source unit testing tool and is used widely for testing small and large units of code. There is no need to create a class object or to define the main method to run JUnit. Assertion libraries provided by JUnit will evaluate the tests. JUnit annotations are used to run the tests. Usually, JUnit is used to run test suites having multiple test cases.
Adding JUnit Library in Java Project
Adding JUnit library in Java Project is a simple process involving five steps.
- Right click on “Java Project” then on “Build Path” and then on “Configure Build Path.
- A new window will be opened. Click on “Libraries” and then on “Add Library”
- Another window will get opened and now click on “JUnit”
- Select “JUnit 4” and then click on “Finish”
- Now click on the “OK” button
JUnit Annotations Used in Selenium Scripts
Many annotations are available in JUnit and here in this article, we discuss a few of them which are most widely used.
- @Test: – Used to run JUnit test and can run by navigating to “Run” and then clicking “Run as JUnit Test”.
- @Before: – Used to run any specific test before each test.
- @BeforeClass: – This is a static method and will run before running all tests.Initialization of properties files, databases etc are done in this method.
- @After: – This method executes after each test
- @AfterClass: – Method will be executed after the completion of all tests. This is also a static method.
- Parameterized JUnit Class: – This is used to run the same scenario with multiple databases.
There are many JUnit Assertions and here we are discussing the most widely used ones only
- JUnit assertEquals: – This is used to check whether two values are equal and the assertion will get failed if the values are unequal.
- JUnit assertTrue: – This will return “True” when the condition is true and the assertion will get failed when the condition is false.
- JUnit assertFalse: – This will return “True” when the condition is false and the assertion will get failed when the condition is true.
JUnit is very easy to learn and simple to use and that is why most of the programmers prefer it. A green or red bar will show the actual test result.