Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin internal members not accessible from alternative test source set in Gradle

Following https://docs.gradle.org/current/userguide/java_testing.html#sec:configuring_java_integration_tests and https://www.michael-bull.com/blog/2016/06/04/separating-integration-and-unit-tests-with-gradle we are attempting to separate our integration tests from plain unit tests.

The problem we have is internal members in Kotlin are not accessible from such tests. As per Kotlin doco there is a visibility exception for test source sets.

The internal visibility modifier means that the member is visible within the same module. More specifically, a module is a set of Kotlin files compiled together:

  1. an IntelliJ IDEA module;
  2. a Maven project;
  3. a Gradle source set (with the exception that the test source set can access the internal declarations of main);
  4. a set of files compiled with one invocation of the Ant task.

Is there a way around it other than not trying to access them? That would call for a major refactoring of hundreds of tests and potentialy the whole codebase.

like image 349
Kousalik Avatar asked Jul 16 '19 05:07

Kousalik


1 Answers

I was able to get a custom test sourceSet to access internal classes by adding the following code to my custom Gradle plugin.

NamedDomainObjectContainer<KotlinWithJavaCompilation<KotlinJvmOptions>> compilations = project
  .getExtensions()
  .getByType(KotlinJvmProjectExtension.class)
  .target.getCompilations();

compilations.getByName(sourceSet.getName())
  .associateWith(compilations.getByName(SourceSet.MAIN_SOURCE_SET_NAME));

I looked at the kotlin-gradle-plugin source code and found the following: https://github.com/JetBrains/kotlin/blob/v1.3.61/libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/KotlinPlugin.kt#L488-L490

With change, the tests in my custom source set run just fine, but IntellIJ still shows compilation errors. I'll look further to see if I can make IntelliJ happy as well

like image 93
gaiazov Avatar answered Nov 17 '22 23:11

gaiazov