When to use a Mocking Framework?

后端 未结 6 551
挽巷
挽巷 2021-01-02 18:52

So I am playing around with mocking frameworks (Moq) for my unit tests, and was wondering when you should use a mocking framework?

What is the benefit/disadvantage b

6条回答
  •  轮回少年
    2021-01-02 19:41

    There are some rules I use writing unit-tests.

    1. If my System Under Test (SUT) or Object Under Test has dependencies then I mock them all.
    2. If I test a method that returns result then I check result only. If dependencies are passed as parameters of the method they should be mocked. (see 1)
    3. If I test 'void' method then verifying mocks is the best option for testing.

    There is an old one article by Martin Fowler Mocks Aren't Stubs.

    In first test you use Mock and in the second one you use Stub.

    Also I see some design issues that lead to your question.

    If it is allowed to remove AkaName from AkaNames collection then it is OK to use stub and check state of the person. If you add specific method void RemoveAkaName(string name) into Person class then mocks should be used in order to verify its invocation. And logic of RemoveAkaName should be tested as part of Person class testing.

    I would use stub for product and mock for repository for you code.

提交回复
热议问题