Android Unit Testing - Intro into JUnit5

Course

Writing Unit Tests

The course uses JUnit5 as the testing framework. I've generally used JUnit4 for my tests at work since they're usually older. There are some things I can draw on - concepts and principles. There are also some differences in features and syntax.

These notes will just cover what I'm learning so this post won't be how to convert from JUnit4 to JUnit5.

Basic Test

Here are some of the basic annotations for JUnit5.

@Before // Runs before the whole test
fun testSetup() {

}

@BeforeEach // Runs before each test
fun testSetup() {

}

@Test // Marks a test
fun testSomething() {

}

Assertions

The course uses the AssertK library for assertions.

Repeating Tests

Repeats a test a number of times. This is particularly useful for tests that are flaky.

@RepeatedTest(10)
fun testSomething() {

}

Parameterized Tests

These tests run the same test with different parameters.

@ParameterizedTest
@ValueSource(strings = ["", " ", "   "])
fun testSomething(value: String) {

}

Testing private functions

Shouldn't really be needed but you can use the @VisibleForTesting annotation to make a function visible to the test. This creates a Lint warning every time the function is used outside of the test. Source

@VisibleForTesting
fun testSomething() {

}

Ideally you'd want to test the public function that calls the private function.