JUnit
JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks which is collectively known as xUnit that originated with JUnit.
In the past, we have been testing our code by running the program and manually checking the output. This is not a scalable solution, as we would have to manually check the output of every function we write. Instead, we can use JUnit to automate this process.
Testing Types
Unit Tests
Unit tests are small, isolated tests that check the functionality of a single method or class. They are typically written in the same language as the code being tested, and are run automatically to verify that the code behaves as expected.
Integration Tests
Integration tests check the interaction between multiple components of a system. They are typically larger in scope than unit tests, and may involve multiple classes or methods working together.
Transparent Tests
Transparent tests are tests that check the internal state of a class or method. They are typically used to verify that the internal state of a class or method is correct, and may involve checking the values of private variables or the state of the object.
Opaque Tests
Opaque tests are tests that check the external behavior of a class or method. They are typically used to verify that the external behavior of a class or method is correct, and may involve checking the output of a method or the state of an object.
JUnit Syntax
In order for JUnit to detect the tests, we need to use the @Test annotation. This annotation tells JUnit that the method is a test method, and should be run when the tests are executed.
Additionally, tests must be public and void, and cannot take any parameters. static methods will not be detected by JUnit.
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MyTest {
@Test
public void testMethod() {
// Arrange
int expected = 5;
int actual = 2 + 3;
// Act
// (no action needed in this case)
// Assert
assertEquals(expected, actual);
}
}
Attributes
Do not expect tests to run in any particular order. JUnit will run the tests in a random order, so do not rely on the order of execution.
When an error or assertion fails occurs, JUnit will stop executing the test at that point and report the error.
Connections
Obvious technical and formatting errors repaired.