Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can we Unit Test Repository class in Flutter without Mocking?

class Repository{
  final NetworkManager networkManager;
  const Repository({required this.networkManager});

  TodoModel? getTodo(){
    if (networkManager.isNetworkAvailable()){
      return const TodoModel(id: 1, todo: "todo", completed: true, userId: 123);
    }
    else{
      return null;
    }
  }
}

class NetworkManager{
  bool isNetworkAvailable(){
    return true;
  }
}
  1. What should be the right approach to Test the getTodo() method in the Repository class ?

  2. What do I need to mock here ?

  3. Can we Unit Test actual API calls and response without mocking anything or without using mocking libs ?

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

>Solution :

Unit Testing is the act of testing pieces of your code. Usually that will include programming logic, expected paths given certain inputs.

For your case, I assume the NetworkManager is not implemented by you, that the code you posted is only an example. Therefore, to test this Repository you would need to mock NetworkManager, which is a separate class, set an expected return value for the isNetworkAvailable(), and pass the mock into the constructor of Repository.

If you needed to test the behavior of the NetworkManager, you would create a separate testing file only for that class.

For your 3rd question, you would need Integration Tests, which is a way of testing multiple parts working together, ideally without mocking anything. As the Flutter docs put it:

Integration tests verify the behavior of the complete app. This test can also be called end-to-end testing or GUI testing.

You can read more about here on the Flutter Docs – Integration testing concepts.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading