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:
junit junit 4.13.2 test
Create test class
For each class you want to test, you need to create a test class with the same name, with the suffixTest
. For example, for a class namedMyClass
, the test class would beMyClassTest
.
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 theadd
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. Theadd
method is called with the input values1
and2
.result
The variable stores the value returned by the method.assertEquals
The assertion method checks whether the actual resultresult
is equal to the expected result3
.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 followingAverageCalculator
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!