Small tips about Unit Tests on Android Projects

Small tips about Unit Tests on Android Projects

Tests are always a great way to make sure that our code works. So, for this reason, the first kind of test that comes into my mind to talk about is ?? Unit Tests ?? . I think they are a cheap tool that every developer can have in their own hands ??.

Write tests is a good practice that you can add to your daily routine as a developer.

In the real world, it is hard for us to keep 100% of code coverage ??. But this is not a reason for you don't have ??????????% of code coverage in your critical code regions ????????.

What are the critical code regions in your project?

I don't know, but you should check the parts that you have:

  • nightmares ??
  • more than one responsibility ???♀?
  • a lot of dependencies ??
  • ...

AAA Pattern

I recommend anyone go deep taking a look at How to structure a unit test: the Arrange-Act-Assert pattern. I prepared an example bellow showing the approach.

Example of a Kotlin Code implementing the AAA Pattern

In the example above, we can see a code used to create a new EquationBufferHandler object inside the arrange block. In this block, we also define the state to be tested, an array with an invalid position. After this declaration, in the act block, the target method is called. This method returns a value that we will check later in the assert block.

Libraries

Truth

This is a great library provided by google, you can check the repository here. The main idea behind this library is create intuitive assert statements instead of our old friend Assert. For example:

  • Assert
Common way using Asserts provided by the JUnit package




  • Truth
Using the Truth Library to make the asserts looks nice




MockK

MockK is a mocking library for Kotlin. I started using this for my projects. The library is simple and very effective supposed to do the same what Mockito does. The great thing that mockK works perfectly with Koin. You can create a class where your unit tests can extend.

No alt text provided for this image









Conclusion

Unit tests are a great tool ??? against bugs??. As good developers, we should always have this in our toolbox ??.

It is not enough for a project to have unit tests. CI must execute the Unit Tests when a PR opens to make sure that nothing broke.

If you have any tips, please tell me I always want to learn about Unit Tests.

要查看或添加评论,请登录

Gabriel Bronzatti Moro的更多文章

社区洞察

其他会员也浏览了