Unit Testing static classes and methods in Java
Gabi
Posted on April 14, 2020
Hello, I wanted to share a situation I found a couple of days ago, whilst working for my project for Twilio April Hackathon. I was working on the server-side project and creating endpoints for my product roadmap. What I insist on is testing my code, especially the logic. It's a habit I am actively trying to make.
Let's take this service method that validates a phone number using Twilio API.
We invoke 'fetch' method on com.twilio.rest.lookups.v1.PhoneNumber to receive an instance of PhoneNumberFetcher.class which will later get all the information on the provided phone number if it exists. Great!
Now, how do we test this? We cannot. We cannot mock static classes. So, we need a way to 'inject' our Twilio API call into our logic and test our code as is without worrying about the response from the external API.
Check the wrapper below:
Now, we can update our service method:
*Create getter and setter for TwilioSmsApiWrapper class
Now we can happily create a unit test for our service method:
That's it. Now you have decoupled you ThirdParty Logic from your service and you can unit test your logic without relying on real API calls.
Happy coding.
Posted on April 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.