23
NovBlack Friday Deal : Up to 40% OFF! + 2 free self-paced courses + Free Ebook - SCHEDULE CALL
All of you know What is QA testing? QA testing, or Quality Assurance testing, is the process of making sure that the products you’re offering to your customers are of the highest possible quality. These techniques are used to prevent various issues with your software products or services. QA testing ensures excellent UX for your customers.
QA Testers are essential in the software development life cycle since they are responsible for testing, tuning, debugging, and suggesting detailed enhancements that guarantee the finished product's playability and quality. Today there are top 5,000+ Qa Tester jobs in the United States. Hence you should grasp this opportunity by enhancing your QA skills. Join QA online courses to master the software testing skills and be job ready! JanBask Training offers Online Certification Courses for Quality Assurance that helps in expanding your QA testing skills.
This tutorial will help the software testing aspirants with the usage of JUnit in unit testing while working with Java. The tutorial is designed for beginners to help them understand the basic functionality of JUnit.
It is a unit testing framework for the Java programming language. JUnit has been crucial in the development of test-driven development and is one of a family of unit testing frameworks. The primary usage of JUnit is to write repeatable tests for your application code units. JUnit stimulates the idea of “testing first, then coding,” which accentuates on setting up of the test data for the code snippets that can be tested first and then implemented. The test approach explicates –
test a little + code a little = JUnit
JUnit increases the productivity of a programmer and the stability of the program’s code snippets, which reduces the time of the tester, which is spent on debugging of the code.
Features of JUnit
Local Environment Setup
JUnit is a framework for Java, so the very first requirement is to have JDK installed on your machine.
System Requirements
JDK |
1.5 or above. |
Memory |
No minimum requirement. |
Disk Space |
No minimum requirement. |
Operating System |
No minimum requirement. |
First of all, open the console and execute a java command based on the operating system you are working on.
OS |
Task |
Command |
Windows |
Open Command Console |
c:\> java -version |
Linux |
Open Command Terminal |
$ java -version |
Mac |
Open Terminal |
machine:~ joseph$ java -version |
Let's verify the output for all the operating systems −
OS |
Output |
Windows |
java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) |
Linux |
java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) |
Mac |
java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101) |
If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link https://www.oracle.com. We are assuming Java 1.8.0_101 as the installed version for this tutorial.
Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example-
OS |
Output |
Windows |
Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.8.0_101 |
Linux |
export JAVA_HOME = /usr/local/java-current |
Mac |
export JAVA_HOME = /Library/Java/Home |
Append Java compiler location to the System Path.
OS |
Output |
Windows |
Append the string C:\Program Files\Java\jdk1.8.0_101\binat the end of the system variable, Path. |
Linux |
export PATH = $PATH:$JAVA_HOME/bin/ |
Mac |
not required |
Verify Java installation using the command java -version as explained above.
Download the latest version of the JUnit jar file from http://www.JUnit.org. At the time of writing this tutorial, we downloaded JUnit-4.12.jar and copied it into C:\>JUnit folder.
OS |
Archive-name |
Windows |
JUnit4.12.jar |
Linux |
JUnit4.12.jar |
Mac |
JUnit4.12.jar |
Set the JUNIT_HOME environment variable to point to the base directory location where the JUNIT jar is stored on your machine. Let’s assume we've stored JUnit4.12.jar in the JUNIT folder.
Sr. No |
OS & Description |
1 |
Windows Set the environment variable JUNIT_HOME to C:\JUNIT |
2 |
Linux export JUNIT_HOME = /usr/local/JUNIT |
3 |
Mac export JUNIT_HOME = /Library/JUNIT |
Set the CLASSPATH environment variable to point to the JUNIT jar location.
Sr.No. |
OS & Description |
1 |
Windows Set the environment variable CLASSPATH to %CLASSPATH%;%JUNIT_HOME%\JUnit4.12.jar;.; |
2 |
Linux export CLASSPATH = $CLASSPATH:$JUNIT_HOME/JUnit4.12.jar:. |
3 |
Mac export CLASSPATH = $CLASSPATH:$JUNIT_HOME/JUnit4.12.jar:. |
Create a java class file name TestJUnit in C:\>JUNIT_WORKSPACE
import org.JUnit.Test;
import static org.JUnit.Assert.assertEquals;
public class TestJUnit {
@Test
public void testAdd() {
String str = "JUnit is working fine";
assertEquals("JUnit is working fine",str);
}
}
Create a java class file name TestRunner in C:\>JUNIT_WORKSPACE to execute test case(s).
import org.JUnit.runner.JUnitCore;
import org.JUnit.runner.Result;
import org.JUnit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJUnit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the classes using javac compiler as follows −
C:\JUNIT_WORKSPACE>javac TestJUnit.java TestRunner.java
Now run the Test Runner to see the result as follows −
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output.
true
To include JUnit into your project, you need to include its dependency into the classpath.
JUnit Maven Dependency
|
JUnit Gradle Dependency
|
JUnit Jar File
Click the link to download the JUnit 4.12 jar file.
JUnit is a Regression testing framework that is used by developers to implement unit testing in Java to escalate the speed of programming and elevate the quality of code. The JUnit framework also allows quick and easy generation of test data and test cases.
The JUnit test framework provides the following important features:-
A fixture is a fixed state of a set of objects which is used as a baseline for running the test cases. The primary purpose of a test fixture is to fortify that there is a well-known and fixed environment in which tests are run so that results are in repeated manner.
The below code will execute two test cases on a simple file.
public class TestCaseFile
{
private File output;
output = new File(...);
output.delete();
public void testFile1()
{
//Code to verify Test Case 1
}
output.delete();
output = new File(...);
public void testFile2()
{
//Code to verify Test Case 2
}
output.delete();
}
There are few issues in the above code-
Let’s compare the same code using JUnit-
public class TestCaseFile
{
private File output;
@Before public void createOutputFile()
{
output = new File(...);
}
@After public void deleteOutputFile()
{
output.delete();
}
@Test public void testFile1()
{
// code for test case objective
}
@Test public void testFile2()
{
// code for test case objective
}
}
The code is now readable and maintainable. The above code structure is Text fixture.
To execute multiple test cases in a specific order, it is done by combining all the test cases in a single origin. The origin is known as test suites.
To run the test suite, you need to annotate a class using the annotations mentioned below-
Below example will run the TestJUnit1.class and TestJUnit2.class
import org.JUnit.runner.RunWith;
import org.JUnit.runners.Suite;
//JUnit Suite Test
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestJUnit1.class ,TestJUnit2.class
})
public class JUnitTestSuite {
}
The Test Runner is used to execute the test cases. Let’s take an assumption of the test cases class TestJUnit.
import org.JUnit.runner.JUnitCore;
import org.JUnit.runner.Result;
import org.JUnit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJUnit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
There are important classes which are used in writing and testing JUnits. Some of them are-
An annotation is a special form of meta-data in a syntactical manner that can be added to Java source code for the better readability and structure. Variables, parameters, packages, methods, and classes can be annotated. JUnit offers the following annotations to write tests:
ANNOTATION |
DESCRIPTION |
@Before |
The annotated method will be run before each test method in the test class. |
@After |
The annotated method will be run after each test method in the test class. |
@BeforeClass |
The annotated method will be run before all test methods in the test class. This method must be static. |
@AfterClass |
The annotated method will be run after all test methods in the test class. This method must be static. |
@Test |
It is used to mark a method as a JUnit test |
@Ignore |
It is used to disable or ignore a test class or method from a test suite. |
@FixMethodOrder |
This class allows the user to choose the order of execution of the methods within a test class. |
@Rule |
Annotates fields that reference rules or methods that return a rule. |
@ClassRule |
Annotates static fields that reference rules or methods that return them. |
JUnit Parameterized test was the new feature that was introduced in JUnit 4. This allows the developer to run the same test, again using different values. A total of five steps are followed to create a parameterized test: -
Let’s look into an example.
|
Create another class TestRunner to compile the program.
import org.JUnit.runner.JUnitCore;
import org.JUnit.runner.Result;
import org.JUnit.runner.notification.Failure;
public class Runner
{
public static void main(String[] args)
{
Result result = JUnitCore.runClasses(PrimeNumberCheckerTest.class);
for (Failure failure : result.getFailures())
{
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Output
Parameterized Number is: 2
Parameterized Number is : 6
Parameterized Number is : 19
Parameterized Number is : 22
Parameterized Number is : 23
true
Normally when you identify an error during execution of the test, you would stop the test, fix the error, and re-run the test. But in the case of JUnit, you can continue with the test execution even when you find an issue or the test fails. ErrorCollector collects all error objects and reports them only once after the test execution is over.
While writing a test script, if you want to execute all the tests even if any line of code fails due to any network failure or any other reason, in that situation, you can continue executing the test script by using a special feature provided by JUnit, which is called ‘error collector.’
JUnit uses @Rule annotation, which is used to create an object of error collector. Once the object is created, you can easily add all the errors into the object using the method addError (Throwable error). Throwable is a superclass of Exception and Error class in Java. When errors are added in this way, these errors will be logged in a JUnit test result.
The major benefit of adding all the errors in an ErrorCollector is that you can verify all the errors at once. And, if the script fails in the middle, it can continue executing it. But yes, it is important to note here that in the case of a try/catch block, using ErrorCollector won’t be possible.
JUnit provides the exception handling of code. You can test whether the code throws a desired exception or not. There are three different ways to test that a method would throw the expected exception:-
1. Set the expected parameter @Test(expected = FileNotFoundException.class).
@Test(expected = FileNotFoundException.class)
public void testReadFile() throws IOException {
FileReader reader = new FileReader("test.txt");
reader.read();
reader.close();
}
2. Using try-catch
@Test
public void testReadFile2() {
try {
FileReader reader = new FileReader("test.txt");
reader.read();
reader.close();
fail("Expected an IOException to be thrown");
} catch (IOException e) {
assertThat(e.getMessage(), is("test.txt (No such file or directory)"));
}
}
3. Testing with ExpectedException Rule.
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testReadFile3() throws IOException {
thrown.expect(IOException.class);
thrown.expectMessage(startsWith("test.txt (No such file or directory)"));
FileReader reader = new FileReader("test.txt");
reader.read();
reader.close();
}
In case of the failure of the test case, the @Ignore annotation helps. A test method annotated with @Ignore will not be executed. Also, if a test class is annotated with @Ignore, then none of its test methods will be executed.
Let’s see the JUnit Ignore test into an action-
package com.mkyong;
import org.JUnit.Ignore;
import org.JUnit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.JUnit.Assert.assertThat;
public class IgnoreTest {
@Test
public void testMath1() {
assertThat(1 + 1, is(2));
}
@Ignore
@Test
public void testMath2() {
assertThat(1 + 2, is(5));
}
@Ignore("some one please create a test for Math3!")
@Test
public void testMath3() {
//...
}
}
In the above code snippet, both testMath()2 and testMath3() will be ignored.
In JUnit, test methods are marked with @Test annotation. To run the method, JUnit first constructs a fresh instance of the class and then invokes the annotated method. JUnit will report any exceptions thrown by the test as a failure. If no exceptions are thrown, the test is assumed to have succeeded.
|
Using JUnit test suites, you can run tests spread into multiple test classes. In JUnit, both @RunWith and @Suite annotations are used to run the suite tests.
|
Assertions help in validating the expected output with the actual output of a test case. All the assertions are in the org.JUnit.Assert class. All assert methods are static, it enables better readable code. JUnit 4 has a set of following assertions: -
Better readability
Better failure messages
Flexibility
Multiple conditions could be asserted using matchers like anyOf or allOf.
|
Assumptions indicate the conditions in which a test is meaningful. A failed assumption does not mean the code is broken but that the test provides no useful information. Assumptions basically mean “don’t run this test if these conditions don’t apply.” The default JUnit runner skips tests with failing assumptions.
|
JUnit is a unit testing framework for Java programming language. With this tutorial, you might have understood the basics of JUnit and How to Download and Install JUnit, JUnit Test Framework, JUnit Annotations & API, JUnit Parameterized Test, JUnit ErrorCollector, JUnit Exception Test, JUnit Ignore Test, Writing Tests in JUnit, JUnit Test Suites, JUnit Assertions, JUnit Assumptions and scaled your unit testing practice like a pro. If not done yet, talk to our counselors at JanBask Training to learn more about QA Testing. Join our Online Certification Courses for Quality Assurance, which will help you broaden your knowledge based on QA techniques and improve your Software QA Tester resume. In order to meet QA experts who can help you improve your testing skills, join our QA Testing Community & Forum.
Happy Testing!
Q1. Why join JanBask Training for Online QA Certification Courses?
Ans. Because our Online QA Certification Courses will help you learn different techniques for performing software testing in a more effective way by getting equipped with project-based work scenarios. You’ll also get acquainted with the practical knowledge of experienced QA professionals. You’ll get world-class infrastructure, one on one industry experts, and a salary hike.
Q2. What is the importance of doing Software Testing certification courses?
Ans. Since the demand for Software Testing is expected to grow at a minimum of 6% by 2026, and there around 13,000 Software Testing job openings are available for QA professionals. In the US, the average income of Software Testers is US$63,070 per year and around ₹370,000 per year in India.
Q3. What are the benefits of Online QA Certification Courses?
Ans. Online QA Certification Courses allow you to learn the techniques of performing software testing in a more effective way by getting equipped with project-based work scenarios. These courses also let you get acquainted with practical knowledge from experienced QA professionals.
Q4. Why offline QA Certification Courses are not considered the best?
Ans. Offline QA Certification Courses aren’t flexible enough like Online QA Certification Courses and they also have longer schedules which affects the planning proposition of professionals as well as the students. This mode of learning is expensive and results in to unplanned utilization of time and resources. Students and professionals might miss out on life-long accessibility to study material, projects, and presentations that are available in online classes. There might be a communication barrier between the instructor and the students.
Q5. How do Quality Assurance Online Courses fills the huge Gap in QA Career Development?
Ans. Our Online QA Certification Courses have a unique curriculum that gives a glimpse of trending methodologies of software testing. Our classes are highly interactive which will not just make you a software tester but also provide you with overall technical expertise in Quality Assurance and make you an expert in this field with hands-on experience.
Q6. What are the eligibility criteria for your Online QA Certification Courses?
Ans. For admission to the Online QA Certification Courses, candidates must have a bachelor’s degree or an equivalent degree and fundamental knowledge of Software Testing, SDLC, and STLC.
Q7. What is the process of Online QA Certification Courses at JanBask Training?
Ans. You have to register, fill up, Pay and submit the application form for online QA Certification Courses and also furnish proof of your academic qualifications & work experience.
Q8. Give an overview of JanBask Training’s QA Testing Professional Entrance Exams.
Ans. The JankBask Training’s QA Certification Professional Entrance Exam is a computer-based test (CBT) that evaluates a candidate's ability to perform software testing with the required skills of an IT professional. The exam focuses on the knowledge, skills, and abilities needed to perform the job duties of an IT professional in a specific organization.
Q9. What are the benefits of the QA Testing Entrance Exam?
Ans. The primary benefit of the QA Testing Entrance Exam is to earn better job opportunities and to work in exceptional teams across big organizations. For that, one needs to be clear of the certification exam because without qualifying for the entrance, the chances of job opportunities will be limited.
Q10. What are the Top QA Specializations offered at JanBask Training?
Ans. We've rounded up top-quality assurance online courses that are sure to help you land your desired specialty like -
With his detailed research and unique insights into IT and Technological trends, Shubham has been producing high-quality and engaging content that meets the standards of its end-users.
Cyber Security
QA
Salesforce
Business Analyst
MS SQL Server
Data Science
DevOps
Hadoop
Python
Artificial Intelligence
Machine Learning
Tableau
Interviews