Home >Java >javaTutorial >JUnit Unit Testing Framework: A Beginner's Tutorial
JUnit is a unit testing framework for Java that provides simple tools to test application components. Once the dependencies are installed, you can test a class by writing a unit test class that contains the @Test annotation and verify expected and actual values using assertion methods such as assertEquals. JUnit provides many features such as prepare methods, failure messages, and timeout mechanisms.
JUnit Unit Testing Framework: Beginner’s Tutorial
Introduction
JUnit is A widely used unit testing framework in the Java language. It provides a concise yet powerful set of tools that enable developers to easily test application components.
Install
Dependency Manager. Add the following line of dependencies:
dependencies { testImplementation "junit:junit:4.13.2" }
If downloading manually, add the junit-4.13.2.jar
file to the class path.
Practical case
Create a simple Java class named Counter
:
public class Counter { int count = 0; public void increment() { count++; } public int getCount() { return count; } }
Next, write a unit Test class CounterTest
to test Counter
class:
import static org.junit.Assert.*; public class CounterTest { @Test public void testIncrement() { Counter counter = new Counter(); // 执行待测试方法 counter.increment(); // 断言预期值和实际值相等 assertEquals(1, counter.getCount()); } }
in testIncrement
method:
The @Test
annotation marks this method as a test method. assertTrue
or assertEquals
to assert that expected results match actual results. Run the test
Run the test from the command line using the following command:
mvn test
Assertion
JUnit provides a variety of assertion methods, including:
assertTrue
: Tests that the actual value is true. assertFalse
: Test that the actual value is false. assertEquals
: Tests that expected and actual values are equal. assertNotEquals
: Tests that the expected value and the actual value are not equal. Other features
The above is the detailed content of JUnit Unit Testing Framework: A Beginner's Tutorial. For more information, please follow other related articles on the PHP Chinese website!