Java unit testing using JUnit: Install JUnit dependencies. Create a test class with the same name, suffix Test, for each class to be tested. Use @Test to annotate the method to be tested. In the test method, create an instance of the class under test, call the method to be tested, and check the expected results using the assert method. Run the test class to execute the tests.
Use unit testing to verify the correctness of Java functions
Introduction
Unit testing is an important and integral practice in software development, used to verify the expected behavior of software components such as functions or classes. This tutorial will walk you through how to use JUnit for unit testing in Java.
Install JUnit
To install JUnit in your project, use the following Maven dependencies:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency>
Create test class
For each class you want to test, you need to create a test class with the same name, with the suffix Test
. For example, for a class named MyClass
, the test class would be MyClassTest
.
Annotation method
Use the @Test
annotation to mark the method to be tested. Each @Test
annotated method is an independent test case.
Example test method
The following example shows a test case for testing the add
method:
public class MyClassTest { @Test public void testAdd() { MyClass myClass = new MyClass(); int result = myClass.add(1, 2); assertEquals(3, result); } }
The test above Medium:
myClass
is an instance of the class under test. The add
method is called with the input values 1
and 2
. result
The variable stores the value returned by the method. assertEquals
The assertion method checks whether the actual result result
is equal to the expected result 3
. Running Tests
Running a test class from the IDE or command line will execute the test cases. The test will succeed if all assertions pass; otherwise, it will fail.
Practical case
Consider the following AverageCalculator
class:
public class AverageCalculator { public double average(int[] numbers) { double sum = 0; for (int number : numbers) { sum += number; } return sum / numbers.length; } }
Supporting test class
public class AverageCalculatorTest { @Test public void testAverage() { AverageCalculator calculator = new AverageCalculator(); double result = calculator.average(new int[]{1, 2, 3, 4}); assertEquals(2.5, result, 0.001); } }
This test case ensures that the calculator correctly calculates the average when given an array of numbers.
The above is the detailed content of How to use unit tests to verify the correctness of Java functions?. For more information, please follow other related articles on the PHP Chinese website!