Write unit tests and UI tests in your Kotlin Multiplatform app!

Anmol Verma
ProAndroidDev
Published in
3 min readJun 4, 2023

--

Recently I have been writing a lot of Kotlin code, and with the code comes the responsibility of delivering high quality and maintainable codebase. Ever since Kotlin Multiplatform aka KMP was released to developers I have been playing around with the expect’s and actual’s.

So getting directly into what type of app I have been building recently ?

So this is a Proof Of Concept that I have been building for potential clients and I wanted to automate something like AmazonGo! You can read more about it in the link here

So the high level features of this app covers

  1. Authentication
  2. User Profile
  3. Scanning Store via QR code : To gain access to the store
  4. Scanning Bar codes: To add items to your cart
  5. Maintaining cart items via SqlDelight
  6. Checkout/Payments

What type of tests have I been writing here ?

  1. ViewModel tests that run on JVM ( Because they can then run on the CI/CD pipeline)
  2. UI tests for the basic flows of the app like login, signup, scanning QR codes etc..
  3. API tests: How well the our API integrates with Ktor and provides proper success/error messages.
  4. Integration Tests: To test how well we integrate our code with SDKs. For ex: Repository and SqlDelight integration.

Sneak Peak into automation tests for Compose UI

Now over to the setup for ViewModel Tests

I had created a Kotlin delegate to provide fakes when needed since my app depends on high level interfaces and not direct implementations It was easy for me to provide Fakes/Mocks

and then the implementation provides fakes or mock variants for these dependencies.

Example: LoginViewModelTest

In the example above you can see that Turbine comes in handy while testing our StateFlows.

Similarly if we look at the shared #JetpackCompose UI test setup, In this setup, I have Ui Tests with automation robots for each screen.

In this setup you can see how we create instances of these Robots for the screens and make use of Kotlin ContextReceivers to call automation methods.

An ideal robot class would have automation methods which allows you to interact with UI elements, and since the data is a fake the tests run faster!

Awesome! That’s all for now 🤓 If you liked this content and want to learn more you can follow me on Twitter and Github , DMs are always open!

Thanks for reading ! 🙇🏻‍♂️

#JetpackCompose #kotlin #Koin #Espresso #KMM #KMP

--

--

Old Seeker, New to Fatherhood, Developer 👨‍💻 with 10 years experience, switching btwn Kotlin ↔️ dart 😬, Dreaming of spaceships 🛸 and extraterrestrials 👽