Mockito: mock POSTMan calls

Learn
2 min readAug 11, 2024

--

I had some POSTMan calls which I was wiring into a spring boot controller to test a few of my services. Can I test these out automatically as part of the build so I don’ t have to test these manually every time?

@MockMvc
That annotation is what you need. You annotate your call with the MockMvc annotation, and you get the test wiring to test out your GET / POST Urls against the same URLs that you were using in POSTMan.

GET versus POST
I hit a snag while doing this with the test throwing an HTTP 400 error. Bad request error. I was not passing a request in my mockito test. That is when I realized that my test controller was just hardcoding the request body. So I just changed my POSTMan endpoints to GET. No reason to continue to have the complexity of dealing with a request body when it is not really being used.

You know what is on the other hand. It is the realization that some day, I would want to test multiple variants of request — with certain fields, without certain fields and the like. When that day comes, these apis would be converted to POST, and the corresponding mockito changes would follow.

Parameterized tests
I had three tests that looked the same except for the end point being invoked. SonarLint asked me to parameterize the tests from a maintainability perspective. So I had one test to replace the three. This parameterized test had a few additional qualifications that the individual tests did not have.

@ParameterizedTest — It had the @ParameterizedTest annotation to indicate that this is a parameterized test.
(strings = <url one> , <url two> , <url three> ) — It had a property called strings which would hold the three url strings within braces.
testMethod(String url) — Then, the test method would have an argument called url into which each individual url would be fed, and the MockMvc would invoke call to that url, and tell you that your tests have passed.

--

--

Learn
Learn

Written by Learn

On a continuing learning journey..

No responses yet