How to test 2 methods with common logic?

前端 未结 2 374
无人及你
无人及你 2021-01-22 04:36

Let\'s say that I have 2 public methods:

func didSelect(data: Data) {
    // do something

    self.view.showText(textForData(data))
}

func didDismiss(data: Dat         


        
2条回答
  •  感动是毒
    2021-01-22 05:12

    I think that the formatting of the data is an own responsibility. So you should extract it to its own class.

    This class could be unit tested on its own.

    Your other class(es) that use this one should be decoupled by using an interface instead of the class directly. The dependancy should be injected (for example in the constrcutor). You could write an default constructor creating the default class to simplify things in production code (poor mens dependency injection).

    Then you could mock the formatter and test the other class(es) in isolation, verifying that the textForData method is called correctly.

提交回复
热议问题