Java testing static class

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.

Top comments (0)

Tailwind CSS Vs Inline CSS: Are They the Same?

Exploring the Power of TypeScript Decorators: Extending and Modifying Code with Ease

Источник

Читайте также:  Java socket connect with timeout
Оцените статью