What have we learned so far
Part 1 – What is Unit Testing?
https://www.onlyfullstack.com/what-is-unit-testing/
JUnit is linked as a JAR at compile-time; the framework resides under package junit.framework for JUnit 3.8 and earlier, and under package org.junit for JUnit 4 and later.
JUnit promotes the idea of “first testing then coding”, which emphasizes on setting up the test data for a piece of code that can be tested first and then implemented. This approach is like “test a little, code a little, test a little, code a little.” It increases the productivity of the programmer and the stability of the program code, which in turn reduces the stress on the programmer and the time spent on debugging.
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency>
How to execute JUnit tests?
1. Using mvn command
# Run all the unit test classes. - mvn test # Run a single test class. - mvn -Dtest=TestApp1 test # Run multiple test classes. - mvn -Dtest=TestApp1,TestApp2 test # Run a single test method from a test class. - mvn -Dtest=TestApp1#testMethod1 test # Run all test methods that match pattern 'testMethod*' from a test class. - mvn -Dtest=TestApp1#testMethod* test # Run all test methods match pattern 'testMethod*' and 'testMagic*' from a test class. - mvn -Dtest=TestApp1#testMethod*+testMagic* test
2. Using Eclipse Run as > JUnit Test
Eclipse Optimize Imports to Include Static Imports
assertEquals(expectedValue, actualValue);
To use asserEquals, we should have a static import as below:
import static org.junit.Assert.assertEquals;
As a developer, it becomes very difficult to add these static imports and to avoid this and add IntelliSense to this static imports we need to configure the Eclipse.
Go to Window > Preferences > Java > Editor > Content Assist > Favorites > New Type
Then add the below imports to have a static import for JUnit.
org.hamcrest.Matchers org.hamcrest.CoreMatchers org.junit org.junit.Assert org.junit.Assume org.junit.matchers.JUnitMatchers
By having those as favorites, if I type “assertT
“ and hit Ctrl+Space, Eclipse offers up asassertThat
a suggestion, and if I pick it, it will add the proper static import to the file.
Source Code
Download the source code of JUnit tutorial from below git repository :
unit-testing-and-integration-testing-with-spring-boot
Let’s go to our next tutorial where we will discuss below points :
Part 3 – Annotations used in JUnit
In this tutorial, we will understand below topics –
– How to define a test in JUnit?
– Annotations used in Junit
1. @Test
2. @Before
3. @After
4. @BeforeClass
5. @AfterClass
6. @Ignore or @Ignore(“Why disabled”)
7. @Test (expected = Exception.class)