简体   繁体   中英

How to unit test the presenter in a mvp-design in flutter when it is dependent on the view?

I want to test the functions of a presenter in an mvp-design in flutter, but I fail to instantiate it for testing because it depends on the view and the view is the state of a stateful widget.

When I give null as view, the function to test fails, bc it tries to call a fuction of the view.

Contract:

abstract class View extends BaseView {

  setSelectedWord(String word);

}

abstract class Presenter {
   toTest(word);
}

Presenter:

class PresenterImpl implements Presenter {
  ///
  View _view;

  @override
  toTest(String word) {
    // do sth.
    _view.setSelectedWord(word);
  }
}

View:

class Screen extends BaseScreen {
  Screen({Key key}) : super(key: key);

  @override
  _State createState() => _State();
}

class _State extends BaseState implementsView {
  ///
  Presenter _presenter;

  setSelectedWord(word){
     //do sth.
   }
}

What is the right way to set up a presenter for testing in this setup?

It is unclear from your sample code exactly how the View instance is being injected into the PresenterImpl , but assuming it is through the constructor you would simply provide a different instance of the View for your unit test, one that does not rely on Flutter.

For example, you could make a MockView class that also extends the View abstract class, this MockView should have no dependencies on Flutter and require no context into the rest of the application.

A simple example could look like:

class MockView extends View {
    String _selectedWord;
    // getter

    setSelectedWord(String word) => _selectedWord = word;
}

presenterTest() {
    String word = "test";
    MockView mockView = MockView();

    PresenterImpl underTest = PresenterImpl(mockView);
    underTest.toTest(word);

    assert(word == mockView.selectedWord);
}

As a side note, testing in this manner is one of the main reasons View and Presenter are abstract, so that we can provide different implementations for testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM