Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dart, unit testing private methods

I have a library which is quite large but only exposes a very tiny API to make it easy to use and learn for new users. I would like to keep my library this way, but I also want to ensure that I have as much unit test coverage as possible, I would like to be able to directly unit test all of my classes but so far as I can tell I can only unit test the public API of the library.

I can, of course, write unit tests to fully test the public methods which will effectively indirectly test all of the underlying private classes, but if a test fails it could mean a lot of digging around in the private code to find out where something went wrong, rather than having unit tests for each individual private class so when something goes wrong it's immediately apparent what went wrong and where.

Is there a design pattern to help with this situation or a way for unit testing to be written for private dart classes and methods?

like image 422
Daniel Robinson Avatar asked Oct 30 '13 08:10

Daniel Robinson


People also ask

How do you test a private method darts?

Create a kind of helper class with this hello method as public. You can then easily unit test it. Let your current class use an instance of this helper class. Test the public methods of your current class which relies on _hello : if this private has a bug, it should be catch by those higher level tests.

Can we test private methods in unit testing?

Unit Tests Should Only Test Public Methods The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.

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 make a Dart function private?

Unlike Java, Dart doesn't have the keywords public, protected, and private. If an identifier starts with an underscore _ , it's private to its library. Libraries not only provide APIs, but are a unit of privacy: identifiers that start with an underscore _ are visible only inside the library.


1 Answers

If you move your private classes into a separate library in the same application then you can make them public and test them. You would then import that library in your current library and not export it (so the user of your library still can't use your other classes as long as he doesn't import that other library himself).

like image 59
Dennis Kaselow Avatar answered Sep 28 '22 06:09

Dennis Kaselow