dimanche 29 décembre 2019

Writing testable codes - Junit Test

Currently working on a project which requires me to write unit test for all the codes that I've implemented. I'm new to writing unit test and have recently picked up the knowledge on writing test cases using annotations like @MockBeans, @InjectMocks, @Spy to help me test out the particular method.

However, sometimes I do struggle with writing test cases which I couldn't mock and it ended up being an integration test. Below are some of the scenario I faced when writing out the test cases.

  1. Unit test for service layer ended up being a integration test as it interacts with the repo layer.

    • The repo layer returns a list of Tuple (javax.persistence.tuple) back to the service layer.
    • Mocked the repo layer, no issue on that.
    • Tried creating the list of Tuple that was supposed to be returned when the repo layer is called through Mockito.when(), however, I could not create the list of tuple as it does not have any setter method.
    • Ended up with a unit test that performing the actual query to the database to retrieve the values out which makes the unit test more like an integration test.
  2. A method which involved a factory method call in it. The factory classes are written as a static class and the returned concrete class are then autowired into spring context using the AutowireCapableBeanFactory

    • Since I could not mock a static factory, I just pass in the value into the factory and let it return the concrete class accordingly.
    • The concrete class returned by the factory could not be mocked.
    • The unit test would end up testing the concrete class as well.
  3. A method that instantiate a new class using new ConcreteClass() instead of @Autowired.

    • I think this is similar to the 2nd scenario I mentioned above.
    • @MockBeans will not work here since the concrete class is not created using @Autowired.

These are the scenario which I'm currently facing, and I spent a lot of time trying to figure out what is the correct way of writing my test cases or rather, how should I design my code in such a way that I could avoid all these issues? Appreciate your feedback and help on these scenarios to improve the way I write my unit test or code design, making it more testable!

Aucun commentaire:

Enregistrer un commentaire