How to deal with interface overuse in TDD?

前端 未结 4 1170
不思量自难忘°
不思量自难忘° 2021-02-01 17:30

I\'ve noticed that when I\'m doing TDD it often leads to a very large amount of interfaces. For classes that have dependencies, they are injected through the constructor in the

4条回答
  •  鱼传尺愫
    2021-02-01 17:49

    Your tests are telling you to redesign your classes.

    There are times when you can't avoid passing complex collaborators that need to be stubbed to make your classes testable, but you should look for ways to provide them with the outputs of those collaborators instead and think about how you could re-arrange their interactions to eliminate complex dependencies.

    For example, instead of providing a TaxCalculator with a ITaxRateRepository (that hits a database during CalculateTaxes), obtain those values before creating your TaxCalculator instance and provide them to its constructor:

    // Bad! (If necessary on occasion)
    public TaxCalculator(ITaxRateRepository taxRateRepository) {}
    
    // Good!
    public TaxCalculator(IDictonary taxRateDictionary) {}
    

    Sometimes this means you have to make bigger changes, adjust object lifetimes or restructure large swaths of code, but I've often found low-lying fruit once I started looking for it.

    For an excellent roundup of techniques for reducing your dependency on dependencies, see Mock Eliminating Patterns.

提交回复
热议问题