JUnit Tests
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class SquareTest{
@Test
public void testSquareConstructorShouldSetLength(){
Square square = new Square(2.0);
assertEquals(2.0, square.getLength());
}
}
Install Parameters Library
dependencies {
// Use JUnit Jupiter API for testing.
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.2',
'org.hamcrest:hamcrest:2.2',
'org.junit.jupiter:junit-jupiter-params'
// Use JUnit Jupiter Engine for testing.
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
// This dependency is used by the application.
implementation 'com.google.guava:guava:29.0-jre'
}
JUnit Parameterized Tests
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class StoveTest{
@ParameterizedTest
@ValueSource(doubles = {1.0, 2.1, 3.2, 4.3, 5.9})
public void SetSquareLengthToPositiveValue(double setting){
Square square = new Square(setting);
assertEquals(setting, square.getLength());
}
}
JUnit Assertions
- assertTrue | assertFalse
- assertEquals | assertNotEquals
- assertArrayEquals
- assertLinesMatch
- assertNull | assertNotNull
- assertSame | assertNotSame
Catching Exceptions
@Test
void exceptionTesting() {
Exception exception = assertThrows(
IllegalArgumentException.class,
() -> new Square(-1.0));
assertEquals("Length cannot be negative",
exception.getMessage());
}
Checking Output
@Test
public void testHelloWorldMain() {
HelloWorld hw = new HelloWorld();
final PrintStream systemOut = System.out;
ByteArrayOutputStream testOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(testOut));
hw.main(new String[]{});
System.setOut(systemOut);
assertEquals(testOut.toString(), "Hello World\n");
}