-1

I am writing junit test cases for a spring boot application. I am having lot of doubts and I have listed them below.

  1. Is it enough to write unit test cases only for service layer?

  2. How to re-use the stubs / mocks created for the models. Each model is created with lot of dependencies. If we don't reuse them, we will be creating the same objects again and again. If we reuse how to accommodate the test values for all test cases?

  3. Is there any best practices when creating the stubs?

  4. Do we need to write the unit test cases for utility methods?

  5. Rest controllers needs unit test cases?

1 Answers1

0

I'll try to give the best general answers, though keep in mind that the specific case might require different approach.

  1. No, generally speaking you should test everything that contains logic which might be subject to maintenance, and therefore unwanted changes.
  2. I'm not quite sure on what is the problem here. The way I understood it, you want to write the stubs/mocks once and use them for multiple tests; maybe, you might use one test class and generate the stubs in a @Before, @BeforeClass annotated methods.
  3. Well, the stub is intended to be used in place of a specific method when provided a given input. So, first, you should identify what inputs your stubbed method is going to receive and be sure you are passing them along (Note: if you provide the wrong inputs the stub won't work). Second, you need to stub the return object or the answer. Anyway, you might need to use sequential stubbing for cases when the method is called multiple times and different returns are required.
  4. Yes, a maintenance change might cause the change in the behavior of such methods heavily affecting the product. You should always use JUnit to constraint the logic. Anyway, utility classes should be trivial and I don't expect it to be difficult for you to test them.
  5. Like I already said, if it contains logic, yes, it should. Anyway I kinda remember there are different frameworks to mock rest calls.

Daniele

Dharman
  • 30,962
  • 25
  • 85
  • 135