Learn how to install JUnit in Linux with this comprehensive guide. Follow our step-by-step instructions to set up JUnit for testing your Java applications efficiently. #centlinux #linux #devops.
Table of Contents
What is JUnit?
JUnit is an open source unit testing framework for Java programming language. JUnit plays a very important role in test-driven development. Junit is linked as a JAR at compile-time. The framework resides under package org.junit for Junit 4 or later. JUnit can be integrated with Apache Ant to create a deployment pipeline for Java applications.
JUnit is a widely used testing framework for the Java programming language. It is essential for developers who want to ensure the quality and functionality of their Java code through automated testing. Here’s a detailed overview of JUnit:
JUnit is a unit testing framework for the Java programming language. It provides a simple way to write and run repeatable tests to verify that code behaves as expected.
Key Features of JUnit
- Framework for Unit Testing: JUnit is designed to test individual units of code, such as methods or classes, to ensure they work as intended.
- Annotations: JUnit uses annotations like
@Test
,@Before
,@After
,@BeforeClass
, and@AfterClass
to define test methods and setup/teardown procedures. - Assertions: It provides a set of assertions (like
assertEquals
,assertTrue
,assertFalse
) to check if the actual results meet the expected outcomes. - Test Suites: JUnit allows you to group multiple tests into a test suite to run them together.
- Integration with Build Tools: It integrates seamlessly with build tools like Maven and Gradle for automated test execution.
- Compatibility: JUnit works with many Java IDEs (like IntelliJ IDEA, Eclipse) and Continuous Integration (CI) systems.
Advantages of Using JUnit
- Improves Code Quality: Automated tests help identify bugs and ensure that new code doesn’t break existing functionality.
- Supports Test-Driven Development (TDD): JUnit encourages writing tests before writing the actual code, which helps design better software.
- Automates Testing: Automates the execution of test cases, saving time and reducing the need for manual testing.
- Documentation: Tests serve as documentation for how code is expected to behave.
Common Use Cases
- Unit Testing: Testing individual methods and classes.
- Integration Testing: Ensuring that different parts of a system work together.
- Regression Testing: Verifying that new changes don’t introduce new bugs.
Conclusion
JUnit is a fundamental tool for Java developers, providing a robust framework for writing and executing tests. Its features support the creation of reliable and maintainable code through automated testing practices.
Recommended Online Training: Junit 5 Jupiter Under JDK 16 In Details Step by Step
Linux Server Specification
In this article, we will install JUnit in Linux and integrate it with Apache Ant.
We have a CentOS 7 virtual machine with following specification:
- Operating System – CentOS 7
- Hostname – junit-01.example.com
- IP Address – 192.168.116.131/24
Install Java on CentOS 7
Connect to junit-01.example.com using ssh.
Install Java Development Kit (JDK) using yum command.
# yum install -y java-1.8.0-openjdk
Install Apache Ant on CentOS 7
Install Apache Ant using yum command.
# yum install -y ant
Verify installation of Java Development Kit (JDK) and Apache Ant.
# java -version openjdk version "1.8.0_191" OpenJDK Runtime Environment (build 1.8.0_191-b12) OpenJDK 64-Bit Server VM (build 25.191-b12, mixed mode)
# ant -version Apache Ant(TM) version 1.9.4 compiled on November 5 2018
Java Development Kit (JDK) and Apache Ant are installed on our CentOS 7 system.
Install JUnit in Linux
Install JUnit in Linux by using yum command.
# yum install -y junit ant-junit
Create a Java Project
Create a directory structure to store Java source and build files. Please read our previous article Install Apache ANT on CentOS 7
# mkdir -p ~/myMathApp/{src/myMathApp,build/classes,build/jar}
Now, Write some Java code.
# vi ~/myMathApp/src/myMathApp/Calculate.java
We write a class Calculate, that perform some basic arithmatic operations. The Java code is as follows:
package myMathApp; public class Calculate { public int sum(int num1, int num2) { return num1 + num2; } public int average(int num1, int num2, int num3) { return (num1 + num2 + num3)/3; } }
Create an Apache Ant build.xml file to compile and run this code with ant command.
# vi ~/myMathApp/build.xml
We are using the same build.xml script that we have used in our previous article.
<project default="run"> <target name="clean"> <delete dir="build" /> </target> <target name="compile" depends="clean"> <mkdir dir="build/classes" /> <javac srcdir="src" destdir="build/classes" includeantruntime="yes" /> </target> <target name="jar" depends="compile"> <mkdir dir="build/jar" /> <jar destfile="build/jar/myMathApp.jar" basedir="build/classes"> <manifest> <attribute name="Main-Class" value="myMathApp.Calculate" /> </manifest> </jar> </target> <target name="run" depends="jar"> <java jar="build/jar/myMathApp.jar" fork="true" /> </target> </project>
You may have notice that, we have adjusted some parameters in build.xml file according to our project.
# cd ~/myMathApp/ # ant Buildfile: /root/myMathApp/build.xml clean: [delete] Deleting directory /root/myMathApp/build compile: [mkdir] Created dir: /root/myMathApp/build/classes [javac] Compiling 1 source file to /root/myMathApp/build/classes jar: [mkdir] Created dir: /root/myMathApp/build/jar [jar] Building jar: /root/myMathApp/build/jar/myMathApp.jar run: [java] Error: Main method not found in class myMathApp.Calculate, please define the main method as: [java] public static void main(String[] args) [java] or a JavaFX application class must extend javafx.application.Application [java] Java Result: 1 BUILD SUCCESSFUL Total time: 1 second
Here run target is throwing an error, because our Java Class lacks a main procedure. There is no need to worry, we already know that, therefore, just ignore this error.
Our Java project is successfully compiled and built with Apache Ant here.
Now, write another Java Class to perform unit testing of our Calculate class.
# vi ~/myMathApp/src/myMathApp/CalculateTest.java
We have write another class CalculateTest for testing Calculate class as follows:
package myMathApp; import org.junit.Test; import static org.junit.Assert.*; public class CalculateTest { Calculate Calculator = new Calculate(); @Test public void testSum() { int sum = Calculator.sum(2,5); int testsum = 7; assertEquals(sum, testsum); } @Test public void testaverage() { int average = Calculator.average(9, 18, 27); int testaverage = 18; assertEquals(average, testaverage); } }
Copy junit class libraries to Project’s lib directory.
# mkdir ~/myMathApp/lib # cp /usr/share/java/junit* lib/ # cp /usr/share/java/ant/ant-junit* lib/
Edit build.xml file to include lib directory to compile target.
<project default="run"> <target name="clean"> <delete dir="build" /> </target> <path id="classpath"> <fileset dir="lib" includes="**/.jar" /> </path> <target name="compile" depends="clean"> <mkdir dir="build/classes" /> <javac srcdir="src" destdir="build/classes" classpathref="classpath" includeantruntime="yes" /> </target> <target name="jar" depends="compile"> <mkdir dir="build/jar" /> <jar destfile="build/jar/myMathApp.jar" basedir="build/classes"> <manifest> <attribute name="Main-Class" value="myMathApp.Calculate" /> </manifest> </jar> </target> <target name="run" depends="jar"> <java jar="build/jar/myMathApp.jar" fork="true" /> </target> </project>
Run ant command again.
# ant Buildfile: /root/myMathApp/build.xml clean: [delete] Deleting directory /root/myMathApp/build compile: [mkdir] Created dir: /root/myMathApp/build/classes [javac] Compiling 2 source files to /root/myMathApp/build/classes jar: [mkdir] Created dir: /root/myMathApp/build/jar [jar] Building jar: /root/myMathApp/build/jar/myMathApp.jar run: [java] Error: Main method not found in class myMathApp.Calculate, please define the main method as: [java] public static void main(String[] args) [java] or a JavaFX application class must extend javafx.application.Application [java] Java Result: 1 BUILD SUCCESSFUL Total time: 1 second
Include a test target in build.xml file to perform unit testing with JUnit.
<project default="run"> <target name="clean"> <delete dir="build" /> </target> <path id="classpath"> <fileset dir="lib" includes="**/.jar" /> </path> <target name="compile" depends="clean"> <mkdir dir="build/classes" /> <javac srcdir="src" destdir="build/classes" classpathref="classpath" includeantruntime="yes" /> </target> <target name="test" depends="jar"> <junit printsummary="yes"> <classpath> <path refid="classpath" /> <path location="build/jar/myMathApp.jar" /> </classpath> <batchtest fork="yes"> <fileset dir="src" includes="**/*Test.java" /> </batchtest> </junit> </target> <target name="jar" depends="compile"> <mkdir dir="build/jar" /> <jar destfile="build/jar/myMathApp.jar" basedir="build/classes"> <manifest> <attribute name="Main-Class" value="myMathApp.Calculate" /> </manifest> </jar> </target> <target name="run" depends="jar"> <java jar="build/jar/myMathApp.jar" fork="true" /> </target> </project>
Run Ant Job for test target.
# ant test Buildfile: /root/myMathApp/build.xml clean: [delete] Deleting directory /root/myMathApp/build compile: [mkdir] Created dir: /root/myMathApp/build/classes [javac] Compiling 2 source files to /root/myMathApp/build/classes jar: [mkdir] Created dir: /root/myMathApp/build/jar [jar] Building jar: /root/myMathApp/build/jar/myMathApp.jar test: [junit] Running myMathApp.CalculateTest [junit] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.018 sec BUILD SUCCESSFUL Total time: 1 second
test target performs two tests and both tests are successful.
To test it, produce a logical error in Calculate.java class.
package myMathApp; public class Calculate { public int sum(int num1, int num2) { return num1 - num2; } public int average(int num1, int num2, int num3) { return (num1 + num2 + num3)/2; } }
Run Ant Job again after producing some logical errors in Calculate.java.
# ant test Buildfile: /root/myMathApp/build.xml clean: [delete] Deleting directory /root/myMathApp/build compile: [mkdir] Created dir: /root/myMathApp/build/classes [javac] Compiling 2 source files to /root/myMathApp/build/classes jar: [mkdir] Created dir: /root/myMathApp/build/jar [jar] Building jar: /root/myMathApp/build/jar/myMathApp.jar test: [junit] Running myMathApp.CalculateTest [junit] Tests run: 2, Failures: 2, Errors: 0, Skipped: 0, Time elapsed: 0.023 sec [junit] Test myMathApp.CalculateTest FAILED BUILD SUCCESSFUL Total time: 2 seconds
You may notice that, both tests are FAILED now.
We have successfully install JUnit in Linux and integrate it with Apache Ant.
If you are new to Linux and facing difficulty in working at Linux Bash prompt. We recommend that, you should read The Linux Command Line, 2nd Edition: A Complete Introduction by William Shotts.
Final Thoughts
Installing JUnit in Linux is a straightforward process that enhances your ability to test Java applications efficiently. By following this guide, you should have JUnit set up and ready to use.
If you need further assistance or professional support with your JUnit installation or other technical tasks, feel free to check out my services on Fiverr. I offer expert solutions to meet your development and testing needs.
Hire me on Fiverr for professional help and quality service.