Business Driven Testing For Spring Boot Applications — Part 3

sukalpo mitra
3 min readJun 2, 2021

Hi all! I am back with my last and final part of the BDT trilogy. And as mentioned, this last part will be super short and will have no connection with BDT. If you can recall during the first part of this series, I told you that I mix Cucumber-Junit with Vanilla Junit. I use whatever is necessary for the given scenario.

This brings me to the subject of this post. I have seen a lot of developers using a public access modifier when it makes more sense to use a private method. When I probe them on it, their answers tend to lean towards the need to test the method. In order to do so, they have to make it public. I generally do not like this thought process. To me, the access modifier of a method should not be directed by my intention of testing it. If I have to test it, I will test it even if it is private. In this final part of my blog, I will show how we can test a private method using Junit.

I will use the same repo I have used to show how I implemented Cucumber with Spring Boot, and it can be accessed here. Let us assume that, in our service class after the third party service is called, we call another method that may change the final message that is sent to the client, depending on the message sent from the third party service. Now the third party service can return as “Hello World” or a plethora of other different messages depending on some logic that is encapsulated from us. What our method does is, if it gets a message as “Hello World,” then it returns “Hello World,” else “Goodbye World”. Let’s add this logic as a private method and call it from our service method.

All set? Let’s push it to git (Commit 61bba4301f84ecb38c43ddd36490a0c6fc6692e6 ).

Now let’s add a test for this private method. So let’s understand what we need to do here. We need to use reflection to temporarily change the access modifier of the method under test. Then we invoke the method and assert the returned response. That’s it! It’s as simple as that! Let’s code it up. This is how we have written the test.

Let’s push it to git and then discuss the most important parts (Commit dd45436e6895f1b662a50c2ad19c8cd4cce6ce4c).

Now let’s discuss what we are doing in the method “invokePrivateMethod”. Using reflection API, we get the intended declared method of BdtService class by passing the method name and the method argument. Once we have gotten a handle on this method, we set its accessibility to true by the setAccessible method. And lastly, we invoke the method by passing the object of the BdtService class and the actual method argument. And that’s how you do it! Simple ain’t it? ;). I hope this three-part series helps some of you during your endeavours with producing good quality code. Until we meet again. Signing off!

--

--