Junit Framework:Its java unit testing framework.maily used for unit testing purpose.
Latest version of Junit is:jupitor junit (junit 5)
Annotation:it provides metadata to the classes and methods.Annotation starts with symbol @ followed by name.
Junit 5 is the latest version --that name is Jupiter Junit
Annotations:
Junit 4 Jupiter Junit
@BeforeClass or @BeforeAll
@Before or @BeforeEach
@Test
@Test
@After @AfterEach
@AfterClass @AfterAll
@Ignore @Disabled
@Runwith @Runwith
@Suite @Suite
@BeforeClass:first this block of code will execute only once before executing any test method
only precondition steps for test method should be written inside this block
Syntax:
@BeforeClass/@BeforeAll
public static void methodName(){
//precondition code
}
@Before:this annotated method will execute before every test method
@Before/@BeforeEach
public void setUp(){
//write the code
}
@Test:only test steps should be written inside this method
we can write more than one @Test annotations in junit/testNG class.
@Test
public void testMethodName(){
//only test steps
}
@Test
public void test2(){test steps code}
Note:you can write multiple @Test annotations but method name must be different
@After:this annotated method will be executed after each test method
@After/@AfterEach
public void tearDown(){
//destroycode
}
@AfterClass:this annotated method will be executed after all the test methods of the class
@AfterClass/@AfterAll
public static void afterClass(){
//destroycode
}
@Ignore:if you want to ignore the execution of any test method, just write @Ignore above the @Test annotation
@Ignore
@Test
public void test1(){}
Execution order
@BeforeClass/@BeforeAll
.
.
.
@Before/@BeforeEach
.
.
@Test
.
.
@After/@AfterEach
.
.
@Before(if one more test method is there)/@BeforeEach
.
.
@Test(2nd test method)
.
.
@After/@AfterEach
.
.
@AfterClass/@AfterAll
Features :
- JUnit is an open source framework which is used for writing & running tests.
- Provides Annotation to identify the test methods.
- Provides Assertions for testing expected results.
- Provides Test runners for running tests.
- JUnit tests allow you to write code faster which increasing quality
- JUnit is elegantly simple. It is less complex & takes less time.
- JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results.
- JUnit tests can be organized into test suites containing test cases and even other test suites.
- Junit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.
- The
@Category
annotation has been replaced by the @Tag
annotation.
- JUnit 5 adds a new set of assertion methods.
- Runners have been replaced with extensions, with a new API for extension implementors.
- JUnit 5 introduces assumptions that stop a test from executing.
- JUnit 5 supports nested and dynamic test classes.
====================================================================
The Assertions class and its methods
The org.junit.jupiter.api.Test
annotation denotes a test method. Note that the @Test
annotation now comes from the JUnit 5 Jupiter API package instead of JUnit 4's org.junit
package. The testConvertToDecimalSuccess
method first executes the MathTools::convertToDecimal
method with a numerator of 3 and a denominator of 4, then asserts that the result is equal to 0.75. The org.junit.jupiter.api.Assertions
class provides a set of static
methods for comparing actual and expected results. The Assertions
class has the following methods, which cover most of the primitive data types:
assertArrayEquals
compares the contents of an actual array to an expected array.
assertEquals
compares an actual value to an expected value.
assertNotEquals
compares two values to validate that they are not equal.
assertTrue
validates that the provided value is true.
assertFalse
validates that the provided value is false.
assertLinesMatch
compares two lists of String
s.
assertNull
validates that the provided value is null.
assertNotNull
validates that the provided value is not null.
assertSame
validates that two values reference the same object.
assertNotSame
validates that two values do not reference the same object.
assertThrows
validates that the execution of a method throws an expected exception (you can see this in the testConvertToDecimalInvalidDenominator
example above).
assertTimeout
validates that a supplied function completes within a specified timeout.
assertTimeoutPreemptively
validates that a supplied function completes within a specified timeout, but once the timeout is reached it kills the function's execution.
--------------------------------------------------------------------------------------------------------------------
Running your unit test
In order to run JUnit 5 tests from a Maven project, you need to include the maven-surefire-plugin
in the Maven pom.xml
file and add a new dependency. Listing 3 shows the pom.xml
file for this project.
Listing 3. Maven pom.xml for an example JUnit 5 project
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javaworld.geekcap</groupId>
<artifactId>junit5</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M4</version>
</plugin>
</plugins>
</build>
<name>junit5</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.6.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
JUnit 5 dependencies
JUnit 5 packages its components in the org.junit.jupiter
group and we need to add the junit-jupiter
artifact, which is an aggregator artifact that imports the following dependencies:
junit-jupiter-api
defines the API for writing tests and extensions.
junit-jupiter-engine
is the test engine implementation that runs the unit tests.
junit-jupiter-params
provides support for parameterized tests.
Next, we need to add the maven-surefire-plugin
build plug-in in order to run the tests.
Finally, be sure to include the maven-compiler-plugin
with a version of Java 8 or later, so that you'll be able to use Java 8 features like lambdas.
Run it!
Use the following command to run the test class from your IDE or from Maven:
mvn clean test
If you're successful, you should see output similar to the following:
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.javaworld.geekcap.math.MathToolsTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.04 s - in com.javaworld.geekcap.math.MathToolsTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.832 s
[INFO] Finished at: 2020-02-16T08:21:15-05:00
[INFO] ------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
New in JUnit 5: Tags
Before wrapping up this introduction to the core of JUnit 5, I'll show you how to use tags to selectively run different test cases in different scenarios. Tags are used to identify and filter specific tests that you want to run in different scenarios. For example, you can tag a test class or a test method as an integration test and another as development. The names and uses of the tags are all up to you.
We'll create three new test classes and tag two of them as development and one as production, presumably to differentiate between tests you want to run when building for different environments
Listing 6. Tags, Test 1 (TestOne.java)
package com.javaworld.geekcap.tags;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@Tag("Development")
class TestOne {
@Test
void testOne() {
System.out.println("Test 1");
}
}
Listing 7. Tags, Test 2 (TestTwo.java)
package com.javaworld.geekcap.tags;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@Tag("Development")
class TestTwo {
@Test
void testTwo() {
System.out.println("Test 2");
}
}
Listing 8. Tags, Test 3 (TestThree.java)
package com.javaworld.geekcap.tags;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@Tag("Production")
class TestThree {
@Test
void testThree() {
System.out.println("Test 3");
}
}
Tags are implemented through annotations, and you can annotate either an entire test class or individual methods in a test class; furthermore, a class or a method can have multiple tags. In this example, TestOne
and TestTwo
are annotated with the "Development" tag, and TestThree
is annotated with the "Production" tag. We can filter test runs in different ways based on tags. The simplest of these is to specify a test in your Maven command line; for example, the following only executes tests tagged as "Development":
mvn clean test -Dgroups="Development"
The groups
property allows you to specify a comma-separated list of tag names for the tests that you want JUnit 5 to run. Executing this yields the following output:
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.javaworld.geekcap.tags.TestOne
Test 1
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.029 s - in com.javaworld.geekcap.tags.TestOne
[INFO] Running com.javaworld.geekcap.tags.TestTwo
Test 2
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 s - in com.javaworld.geekcap.tags.TestTwo
Likewise, we could execute just the "Production" tests as follows:
mvn clean test -Dgroups="Production"
Or both "Development" and "Production" as follows:
mvn clean test -Dgroups="Development, Production"
Test suite Test suite means bundle a few unit test cases and run it together. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.
example:
@RunWith(Suite.class)
@Suite.SuiteClasses({ TestJunit1.class ,TestJunit2.class })
Limitations of Junit:
1)dependent testcases cannot be executed
2)you cannot prioritize the test cases
3)you dont have an option to do datadriven testing with an annotation.