Introduction to Unit Testing - anastasiamexa/Healthy-Coder-App GitHub Wiki
Unit testing is a software testing technique where individual units or components of a software application are tested in isolation. The purpose is to validate that each unit of the software performs as designed. Unit tests are typically written and executed by developers during the development phase.
JUnit is a popular open-source testing framework for Java. It provides annotations to identify test methods, assertions for testing expected results, and test runners for executing tests. JUnit has evolved over time, and JUnit 5 is the latest version that introduces several new features and improvements over its predecessors.
Some key features include:
1. Annotations: JUnit 5 provides a set of annotations to mark methods as test methods, set up and tear down methods, and more. For example, @Test
is used to mark a method as a test method.
2. Assertions: JUnit 5 comes with a variety of assertion methods in the Assertions
class to check expected results. For example, assertEquals
, assertTrue
, assertNotNull
, etc.
3. Test Lifecycle Methods: JUnit 5 supports lifecycle methods such as @BeforeEach (executed before each test), @AfterEach (executed after each test), @BeforeAll (executed once before all tests), and @AfterAll (executed once after all tests).
4. Parameterized Tests: JUnit 5 allows you to write parameterized tests, which run the same test logic with different sets of parameters.
5. Test Suites: You can group multiple test classes into a test suite using @RunWith
or the @SelectClasses
and @SelectPackages
annotations.
To use JUnit 5 in your Java project, you need to include the JUnit dependencies in your build tool. For example, if you're using Maven, you can add the following dependency to your pom.xml
file:
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.0</version>
<scope>test</scope>
</dependency>
</dependencies>
After adding the dependency, you can start writing your test classes and methods using JUnit 5 annotations.
Here's a simple example:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MyMathTest {
@Test
void addTwoNumbers() {
MyMath myMath = new MyMath();
int result = myMath.add(3, 4);
assertEquals(7, result);
}
}
In this example, the @Test
annotation marks the method as a test method, and the assertEquals
method checks if the result of myMath.add(3, 4)
is equal to 7.
This is just a basic introduction, and there's a lot more you can do with JUnit 5, check JUnit 5 User Guide.