Kapt generatestubs - Cannot initialize object with internal constructor from unit-test

Viewed 879

Let say we have a kotlin class defined as:

package foo

class Bar internal constructor() {
//...
}

When I try to init that object from a test method like:

package foo


class TestBar {
    @Test
    fun testingBar() {
        Bar()  //<----- error
    }
}

I get a following error:

Cannot access '<init>': it is internal in 'Bar'

Both Bar and TestBar are in the same AndroidStudio module (android library) Both paths to sources were defined in a gradle:

...
sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
    test.java.srcDirs += 'src/test/kotlin'
}
...

Tests seem to work fine in general, but I'm unable to create any object with a internal constructor.

I'm using:

ext.kotlin_version = '1.1.3-2'

EDIT

Thanks for the feedback. I've decided to make simple android multi-module application from scratch and it worked just fine.

Then I tried to get rid of my module dependencies one by one and it turns out that problem is caused by dagger2 gradle dependency.

dependencies {
    ...

    //dagger 2
    implementation 'com.google.dagger:dagger:2.8'
    kapt 'com.google.dagger:dagger-compiler:2.8'
}

When I remove the dependency I am able to access internal constructor from tests without a problem. Is that an indication of a bug or my dependency is not defined properly?


EDIT 2 (Solution)

It turns out that problem was caused by kapt's generatestubs = true option. In order to make tests see internal classes just switch to a new kapt implementation:

http://kotlinlang.org/docs/reference/kapt.html

which in my case came down to getting rid of

kapt {
    generateStubs = true
}

and adding

apply plugin: kotlin-kapt'

at the beginning of gradle file.

1 Answers
Related