Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Make an internal function visible for unit tests

In case the tests are in a different module than the production code (which is common), what's the best way to make internal functions visible for tests?

In Java, I would have the production code and the test in the same package and make the methods-to-be-tested package-private (plus, add a @VisibleForTest annotation if the only reason for having it package-private rather than private is the test). Unfortunately, Kotlin doesn't have the concept of package-private.

like image 667
Jan Pomikálek Avatar asked Feb 28 '16 14:02

Jan Pomikálek


People also ask

How do you test a private function in Kotlin?

You can't directly test private methods, and you can't make a method private any other way than the keyword private . Either make them internal or only test public API.

Should Kotlin test classes be internal?

Setting a declaration as internal means that it'll be available in the same module only. By module in Kotlin, we mean a group of files that are compiled together. These won't be visible outside the current module. Internal Modifiers is useful when you need to hide specific library implementations from the users.


2 Answers

Classes and methods marked with internal access modifier will work from within current versions of Kotlin, Gradle and also Intellij for accessing those methods from test classes. The tools consider the main and test source paths as part of the same module.

Did you try this already? And if it failed you should report a bug since this was already reported, fixed and should be fine in any current version.

like image 189
Jayson Minard Avatar answered Oct 16 '22 11:10

Jayson Minard


Probably the easiest solution is to place your unit tests depending on internal code in the same module with the production сode and leave only the integration tests, which use public API, in the separate module.

This seems reasonable since the internal modifier means exactly the visibility inside the same module.

like image 7
hotkey Avatar answered Oct 16 '22 11:10

hotkey