Useful design patterns for unit testing/TDD?

后端 未结 9 651
一个人的身影
一个人的身影 2021-01-29 17:54

Reading this question has helped me solidify some of the problems I\'ve always had with unit-testing, TDD, et al.

Since coming across the TDD approach to development I k

9条回答
  •  礼貌的吻别
    2021-01-29 18:43

    A lot of problems like this can be solved with proper encapsulation. Or, you might have this problem if you are mixing your concerns. Say you've got code that validates a user, validates a domain object, then saves the domain object all in one method or class. You've mixed your concerns, and you aren't going to be happy. You need to separate those concerns (authentication/authorization, business logic, persistence) so you can test them in isolation.

    Design patterns help, but a lot of the exotic ones have very narrow problems to which they can be applied. Patterns like composite, command, are used often, and are simple.

    The guideline is: if it is very difficult to test something, you can probably refactor it into smaller problems and test the refactored bits in isolation. So if you have a 200 line method with 5 levels of if statements and a few for-loops, you might want to break that sucker up.

    So, start by seeing if you can make complicated code simpler by separating your concerns, and then see if you can make complicated code simpler by breaking it up. Of course if a design pattern jumps out at you, then go for it.

提交回复
热议问题