1

I want to write some unit tests around an abstract Uploader class that I have written like so:

abstract class Uploader {
  Future<StreamSubscription> subscribe(String filename, void onEvent(Event event));
}

class FirebaseUploader implements Uploader {
  Future<StreamSubscription> subscribe(String filename, void onEvent(Event event)) async {
    String userId = await auth.signInAnonymously();
    DatabaseReference databaseReference = _databaseReference(userId, filename);
    return databaseReference.onValue.listen(onEvent);
  }
}

class UploaderMock implements Uploader {

  Future<StreamSubscription> subscribe(String filename, void onEvent(Event event)) async {

    Event event = new Event(); // The class 'Event' doesn't have a default constructor.
    return Future.value(null);
  }
}

The trouble is, I can't work out how to create my own Events in my UploaderMock, so I can call onEvent. If I try to create a new Event(), I get the following error:

The class 'Event' doesn't have a default constructor.

This is because Event has a private constructor:

Event._(this._data) : snapshot = new DataSnapshot._(_data['snapshot']);

This makes sense for production, but it doesn't really work for testing.

Any ideas? How can I test code that uses StreamSubscription?

bizz84
  • 1,964
  • 21
  • 34

2 Answers2

1

You can implements Event on a custom class.

class Bar {
  Bar._() {}
}

class Foo implements Bar {
  Foo();
}
Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
0

You can't, but you can make them public and annotate it with @visibleForTesting to get an DartAnalyzer warning when they are accessed from code that is not in in the same library or in test/

answered here How to test private functions/methods in Flutter?

Bandss
  • 1
  • 1
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/33363302) – Rohan Jariwala Dec 13 '22 at 15:16
  • thanks for the review, comment changed. – Bandss Dec 13 '22 at 15:46