When to use mock objects in unit tests

后端 未结 5 906
北恋
北恋 2020-12-04 02:27

I\'m aware that there are many questions about mocking and testing, but I didn\'t find any that helped me perfectly, so I still have problems understanding the follwing:

5条回答
  •  清歌不尽
    2020-12-04 02:31

    To answer the first part of your question

    If now I want to unit test my ProcessClass do I consider Citizen as an external feature that has to be mocked, or do I simply just create a Citizen for test purposes?

    Without knowing more about Citizen it is hard to tell. However, the general rule is, that mocking should be done for a reason. Good reasons are:

    • You can not easily make the depended-on-component (DOC) behave as intended for your tests.
    • Does calling the DOC cause any non-derministic behaviour (date/time, randomness, network connections)?
    • The test setup is overly complex and/or maintenance intensive (like, need for external files)
    • The original DOC brings portability problems for your test code.
    • Does using the original DOC cause unnacceptably long build / execution times?
    • Has the DOC stability (maturity) issues that make the tests unreliable, or, worse, is the DOC not even available yet?

    For example, you (typically) don't mock standard library math functions like sin or cos, because they don't have any of the abovementioned problems. In your case, you need to judge whether just using Citizen would cause any of the abovementioned problems. If so, it is very likely better to mock it, otherwise you better do not mock.

提交回复
热议问题