Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test private functions/methods in Flutter?

I'm currently developing an app that uses the bloc architecture. My bloc is using streams exclusively to communicate with the UI. Therefore all its methods except for the constructor are private ( they start by '_').

So the question is how can I test the bloc's private methods from the test class that lives in the text package so it cannot access private methods of other packages.

Thanks

like image 256
onthemoon Avatar asked Jan 16 '19 15:01

onthemoon


People also ask

How do you test private methods in Flutter?

You can import it from Flutter ( package:flutter/foundation. dart exports it.) or add the meta package to dependencies: in pubspec. yaml (and import it from there).

How do you test private methods?

To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.

Can we write tests for private methods?

Why We Shouldn't Test Private Methods. As a rule, the unit tests we write should only check our public methods contracts. Private methods are implementation details that the callers of our public methods are not aware of. Furthermore, changing our implementation details should not lead us to change our tests.


1 Answers

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/

https://github.com/dart-lang/sdk/blob/master/pkg/meta/lib/meta.dart#L224-L233

/// Used to annotate a declaration was made public, so that it is more visible
/// than otherwise necessary, to make code testable.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with a declaration not in the `lib` folder
///   of a package, or
/// * the declaration is referenced outside of its the defining library or a
///   library which is in the `test` folder of the defining package.
like image 56
Günter Zöchbauer Avatar answered Sep 27 '22 20:09

Günter Zöchbauer