- Published on
Android Unit Test: Essential Knowledge
- Authors
- Name
- Dan Tech
- @dan_0xff
Introduction to Unit Test
Unit Test is a proactive testing tool used by Developers on the code they write. In Android, we use JUnit to write Unit Tests for the application. Additionally, other libraries can be used to facilitate implementation. The two most commonly used libraries are Mockito and Mockk. In this course, you will receive detailed instructions on using Mockk to implement Unit Tests for your application.
Importance of Unit Test
Hundreds of reasons could be listed, but I will choose the 3 most valuable reasons to list here.
- Early detection of logical errors: A principle in programming for every programmer is that they must manually execute all the logic they write. To simplify this, we can use Unit Tests to retest the logic we have written before. When the logic is changed, it will affect the Unit Test, leading to errors. This will be an early warning for the Programmer to find the error and fix it before things go too far.
- Increased confidence when changing code: An interesting thing is that when the amount of Unit Tests in your project is large, you will be very confident in your changes. Unit Test starts as a burden when you have to double your workload by both writing Logic and writing Tests for Logic. However, when Unit Tests are numerous enough, it becomes a guardian angel for your updates during Software development.
- A plus for increasing salary and level: No need to explain too much. You are better, contribute more, the company will pay you better, give you more authority.
Mindset for writing Testable Code
Any code can be tested, but some code is easier to write Unit Tests for. Below are a few tips based on my personal experience.
- Write concise functions with clear and specific purposes.
- Always use data class, primary variable, and Interface as params of a function. Do not use a fixed Class because it will affect the scalability of the Code.
- Each function must have at least 2 Tests: test success, test failed