DEV Community

Gabi
Gabi

Posted on • Edited on

2

Unit Testing static classes and methods in Java

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.

Alt Text

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:

Alt Text

Now, we can update our service method:
*Create getter and setter for TwilioSmsApiWrapper class
Alt Text

Now we can happily create a unit test for our service method:

Alt Text

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay