David RomeroSoftware EngineerFor several years I have a hard goal. I want to become a great software engineer, so I work hard developing quality software every day. Fan of new technologies. I will not stop until overcome my goals.
Let’s suppose you have to implement a publisher with Redis and Spring Boot and you have to bringing down the instance when redis is unavailable.
The code could be something like that:
This implementation is fine and It works as we expected but now, we have a problem…We want to test the code, specifically, we want to test booth branches in the publish method.
For that mision, first of all, I created two tests:
Given a message When is published Then is published by redis
Given the Redis instance down When a message is published Then the container is bringing down
That’s right, It’s seems to be fine, now, when we executed the tests something weird occurrs.
Our tests execution are not ending due to the System.exit introduced in the publisher class.
How could I fix this issue?
Solution:
The most obvious answer is trying to mocking System.exit, so, let’s go.
As the javadoc shows us, System.exit method calls the exit method in class Runtime, thus, we should put the focus on that method.
We could create a Runtime Spy and exchange it with the static variable of the Runtine class and when the second test ends, we could leave everything as it was before.
Our test will be as following:
With this improve, our test suite runs fine and we have added an assert to the tests something important and that it did not have before.
Conclusions:
Thanks to Mockito and Java Reflection we can test almost all the cauisics that we find in our day to day.
The full source code for this article is available over on GitHub.