Cheat Sheet

Testing

JUnit 5

gradle

dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' } test { useJUnitPlatform() }
budgie@host:~/$ ./gradlew test
budgie@host:~/$ ./gradlew test --tests "dev.johnwatts.package.TestClass"
budgie@host:~/$ ./gradlew test --tests "dev.johnwatts.package.TestClass.method"

assertions

import static org.junit.jupiter.api.Assertions.*;

annotations

@Test public void foo() @BeforeEach public void foo() // Order of execution of multiple @BeforeEach methods is not guaranteed // Runs before every test is run @BeforeAll public void foo() // Order of execution of multiple @BeforeAll methods is not guaranteed // Runs once before all tests are run @AfterEach // Runs after each test is run; order is not guaranteed @AfterAll // Runs after all tests have completed

mockito

gradle

dependencies { testImplementation ( 'org.junit.jupiter:junit-jupiter-api:5.6.0', 'org.mockito:mockito-core:3.8.0', 'org.mockito:mockito-junit-jupiter:3.8.0' ) testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' } test { useJUnitPlatform() }

usage

import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class ClassToTest { @Mock Foo mockedFoo; @Mock Bar mockedBar; // proceed with caution, these may be a little dodgy @Test public void test() { when(mockedFoo.methodCall()).thenReturn(mockedBar); when(mockedBar.someMethod()).thenCallRealMethod(); doNothing().when(mockedFoo).someVoidMethod(); doThrow(new UncheckedException()).when(mockedBar).needThisToThrow(); verify(mockedFoo).getOutputFor(anyInt()); verify(mockedBar, times(3)).getOutputFor(anyInt()); }