4

After reading several posts and articles about this issue I'm still confused about how to test a method in a VIPER architecture (for example with Swift).

If I had this code:

Presenter class

protocol InteractorToPresenterProtocol: class {

    func showInfo(info: Info)
}

class Presenter {

    private var interactor: PresenterToInteractorProtocol?

    init() {}

    func makeSomeStuffInPresenter() {

        // make some stuff 
        ...
        interactor?.makeSomeStuffInInteractor()
    }
}

extension Presenter : InteractorToPresenterProtocol {

    func showInfo(info: Info) {

       print(info)
    }    
}

Interactor class:

protocol PresenterToInteractorProtocol: class {

    func makeSomeStuffInInteractor()
}

class Interactor {

    private var presenter: InteractorToPresenterProtocol?

    init() {}
}

extension Interactor : PresenterToInteractorProtocol {

    func makeSomeStuffInInteractor() {

       // make some stuff 
       ...
       presenter?.showInfo(info)
    }    
}

How should I test makeSomeStuffInPresenter method?

Wonton
  • 1,033
  • 16
  • 33
  • Make a Presenter and call the method? Unclear where the difficulty lies. – matt Jun 15 '20 at 23:55
  • The reason why this is difficult to me is that the results of makeSomeStuffInInteractor are not returned in that method, instead another method is called.The results of makeSomeStuffInInteractor are really obtained in my presenter showInfo method. – Wonton Jun 16 '20 at 00:01
  • You make an interactor too, or you can use dependency injection to arm yourself with a mock of the interactor. – matt Jun 16 '20 at 00:03
  • Yes, I can inject the interactor and mock it. – Wonton Jun 16 '20 at 07:17

1 Answers1

5

You can check the attached sample.

The basic understanding of viper architecture is below.

View: Manages the view displayed to the user. Interactor : Handles the business logic. Presenter: Controls the communication between View and Interactor. Entities : Are the modal classes. Router: Is responsible for managing the Navigation.

Writing the unit test cases.

For Interactor : You can opt Interactor protocol to a mock class and call it's function with positive and negative cases and your Presenter will fulfil the test case expectation.

For Presenter : Similarly, you can mock Interactor, View and call Presenter function and view will fulfil the test case expectation.

In general, for each zone z in {V,I,P,E,R}, you can mock up to the other 4 with simulated simplistic perfection & repeatability so that the zone-under-test (ZUT) is the only zone whose real source code is being exercised (in isolation).

Andreas ZUERCHER
  • 862
  • 1
  • 7
  • 20
navroz
  • 382
  • 2
  • 13