Why can’t I write unit tests?

Gustavo Werle
2 min readMar 20, 2022

Sometimes, usually when you never wrote a test, writing a unit test seems to be a hard and complex task, but it’s not, there are some explanations to this feeling and we’ll discuss it in this article. When I decided to learn about unit tests I went to the Google Android tests documentation, read a lot, and realized that it seems to be easier than I thought, but when I tried it the test just doesn’t work whatever I tried. A few weeks later, after studying more, I realized that the problem wasn’t in my test, it was in my classes. So if you couldn’t test a class the reason is your class wasn’t following the best practices. A good class is easy to test, but what makes a class easy to test?

  1. You must use dependency injection:

In addition to making your work easier, DI also helps you to write testable classes. If you call a constructor inside your class it’ll be difficult to mock¹ it in the test, although when you put all your dependencies in the constructor, it becomes much easier to pass a fake instance on the tests. Then you can check if these fake instances were called correctly.

2. You must follow the SRP:

If your class has many responsibilities it certainly will be hard to test. So try to keep your class simple, short, and with just one purpose. You can learn more about SRP at the link above.

3. You must not depend on the framework:

In some cases, framework classes could be hard to mock and make your class less testable, so try to avoid depending on the framework in your domain classes. If you can’t try to wrap this dependency in another class, in this way, in addition to making the test easy, you will be safer because if this dependency becomes deprecated you will just need to change it in one class, making the maintenance simple.

When you write a better code, you are able to test it, and the quality of the code improves a lot. Certainly, if you follow these 3 tips and write tests, your application will be easier and easier to maintain, understand, and get bug-free. It’s just my humble opinion based on my experience, if you have a different idea or want to contribute to this topic please leave a comment below. I hope it helped you.

¹Mock: mocks are fake instances of complex objects that simulate the behavior of the real objects. You can find more about mocks here.

--

--