Mocking a class vs. mocking its interface

后端 未结 5 601
南方客
南方客 2020-12-25 10:43

For a unit test, I need to mock several dependencies. One of the dependencies is a class which implements an interface:

public class DataAccessImpl implement         


        
相关标签:
5条回答
  • 2020-12-25 11:30

    In most cases technically there is no difference and you may mock as class so an interface. Conceptually it is better to use interfaces because of better abstraction.

    0 讨论(0)
  • 2020-12-25 11:41

    It may not make much difference in your case but the preferred approach is to mock interface, as normally if you follow TDD (Test Driven Development) then you could write your unit tests even before you write your implementation classes. Thus even if you did not have concrete class DataAccessImpl, you could still write unit tests using your interface DataAccess.

    Moreover mocking frameworks have limitations in mocking classes, and some frameworks only mock interfaces by default.

    0 讨论(0)
  • 2020-12-25 11:43

    You should mock the interface since it will help ensure you are adhering to Liskov Substitution Principal (https://stackoverflow.com/a/56904/3571100).

    0 讨论(0)
  • 2020-12-25 11:46

    If you only use it through interface and it's not a partial mock, there is no difference other than your inner feeling. Mocking the class will also mock non-used public method if the class has them, but that is not a big deal to consider.

    0 讨论(0)
  • 2020-12-25 11:49

    It depends. If your code depends on the class and not on the interface you must mock the class to write a valid unit test.

    0 讨论(0)
提交回复
热议问题