Unit Test Guidelines
Function Naming Convention
-
Unit Test method naming convention should be as follows with enclosed backticks
Given <Preconditions>, When <MethodIsExecuted>, Then <ShouldReturnExpectedResult>
-
Every test method should start with
@Test Annotation
-
Given When Then word first letter should be in uppercase
-
Unit Test method names have character limitations. If the name of the test method is written too long, an error may be received as follows: error while writing …..$1.class (Permission denied...)
@Test
fun `Given an input path with 2 slashes, When getPluginIdFromPath is called, Then check the output`() {
// Test implementation goes here
}
Unit Test Implementation - Given When Then
-
Code blocks within the test method should be split with Given-When-Then comments to make it more readable and understandable.
-
Every code block written to satisfy the preconditions is written under the Given comment. (every block, creating test observers, building expected response/result model, etc.)
-
The method to be tested is called under the When comment.
-
All lines of code related to the validation phase must be placed under the Then comment. ( assertThat, verify blocks, etc.)
@Test
fun `Given an input path with 2 slashes, When getPluginIdFromPath is called, Then check the output`() {
// Given
// When
val pluginId = getPluginIdFromPath("videoconsultation/details/test")
// Then
assertThat(pluginId).isEqualTo("de.navida.pro.videoconsultation")
}
Important
- Try not to use different frameworks in one unit test file
- For mocking, we can use mockk for mocking (io.mockk)
- For asserting use Truth from com.google.common.truth
- We should avoid unit mockk anotation. We should directly use mockk api for initialization
- If we are unit testing viewmodel, then dont mock the viewmodel and test it. That's like we are testing mocking framework. we should only mock its dependencies and test viewmodel