0

I am new to unit testing and still not completely getting it.

Suppose I have a resource /shop/:itemId which calls a service and can throw various response codes like ITEM_NOT_FOUND, SUCCESS, FAILURE, INVALID_EMAIL etc.

I am confused in what should I actually mock and what to test for the api end point? It would be great if you can explain with any small example.

Vid
  • 123
  • 11
  • 1
    It depends. The canonical response is you'd mock the service called by the endpoint to exercise all possible responses. – Dave Newton Nov 17 '21 at 14:08
  • 1
    This community is for specific questions on programming. It is not a place where people write down examples for you ... that you can find in any good book or tutorial. There are no shortcuts. You have to step back and LEARN these concepts. Having said that: first of all, understand that **mocking** is just a tool that helps writing unit tests. You only MOCK things if you need to. So you first look at your product, and figure: what are the contracts? How can I verify them? And then you look at the implemenation ... – GhostCat Nov 17 '21 at 14:09
  • But checking of invalid item id or email is done by the service, so how to test? Just hard code a invalid email and use when return or make it go through the logic? – Vid Nov 17 '21 at 14:10
  • 1
    to then decide: okay, in order to test this aspect, I need to control X over here. And then maybe you use some mocking framework to mock the instance of X in your setup. – GhostCat Nov 17 '21 at 14:10
  • 1
    Again, such things very much depend. Ideally, you do unit tests for all the units that your service is using. You ALWAYS verify all the components individually. SO that in the end, you might focus on doing simple straight forward tests to verify that your INTEGRATION and configuration works as expected. But that also very much depends on the technology stack you are using. For example if it is jersey, there are things like jersey test that allow you to do a almost "fully functional" end to end test of your services. – GhostCat Nov 17 '21 at 14:11
  • 1
    At least share the structure of your project> controllers, beans, repositories, etc. Also check this https://stackoverflow.com/questions/2128148/what-are-mock-objects-in-java and this https://www.vogella.com/tutorials/Mockito/article.html Maybe your question should be: How to configure java project to make it easy to mock? – JRichardsz Nov 17 '21 at 14:12

0 Answers0