Write Unit Test in Kotlin

Latest Android Studio(3.0 Canary 7) allow us to use Kotlin to write source code and test case too. I’ve written a post about how to test kotlin code in java unit test files. Today, I want to talk about how to test kotlin code in kotlin. And it is not as that easy as you might think.

2. init again

Now we want to test a presenter. Still we can not just use private Presenter presenter in kotlin. Besides, the initialization of presenter depends on the view field in the code above.

Here is what we do

public FooTest {
    @Mock lateinit var view: IView
    var presenter : Presenter by lazy {
        Presenter(view)
    }
    
    @Before public void setUp(){
        MockictoAnnotation.init(this); }}Copy the code

4. Robolectric

Some test cases need Robolectric to test some special class. But since the Class object is different between Java and Kotlin.

We may have a little confused about how to import Robolectric. Just like the screenshot below:

Here is what we do:

@RunWith(RobolectricTestRunner: :class)
@Config(constants = BuildConfig: :class, sdk = intArrayOf(Build.VERSION_CODES.LOLLIPOP))
class PresenterTest {Copy the code