SlideShare a Scribd company logo
Unit Testing in Kotlin
Egor Andreevici
Software Developer @ 1&1
@EgorAnd
Android: In The Java Zone
Java Kotlin
+ Official
+ Stable
- Old
- Verbose
+ Modern
+ Expressive
- Stable?
- Support?
Starting with Kotlin on Android?
Start small!
Start with unit tests!
Unit Tests Are Good
Benefits of Unit Tests
Provide a safety net around your code
Document your code… what?
Promote good design practices
Bad Documentation
/**
* Get a subview of the root view at a certain position.
*
* @param position Position, 0 <= position < root child count
* @return Subview at given position, or {@code null} if position is out of
* bounds
*/
public View getViewAtPosition(int position) {
if (position >= 0 && position < root.getChildCount()) {
return root.getChildAt(position);
}
return null;
}
Bad Documentation
/**
* Get a subview of the root view at a certain position.
*
* @param position Position, 0 <= position < root child count
* @return Subview at given position, or {@code null} if position is out of
* bounds
*/
public View getViewAtPosition(int position) {
if (position >= 0 && position < root.getChildCount()) {
return root.getChildAt(position);
}
throw new IndexOutOfBoundsException("Invalid position " + position);
}
A Better Test
@Test public void shouldReturnNullIfCalledWithInvalidPosition() {
doReturn(0).when(mockParent).getChildCount();
assertThat(docs.getViewAtPosition(0)).isNull();
}
EvenBetterTest.kt
Kotlinize
@Test fun shouldReturnNullIfCalledWithInvalidPosition() {
doReturn(0).`when`<ViewGroup>(mockParent).childCount
assertThat(docs.getViewAtPosition(0)).isNull()
}
Better Method Names
@Test fun `Should return null if called with invalid position`() {
doReturn(0).`when`<ViewGroup>(mockParent).childCount
assertThat(docs.getViewAtPosition(0)).isNull()
}
Better Mocking with Mockito-Kotlin
● Reified types for mock creation
● Fluent method mocking syntax
● More niceties
Better Mocking with Mockito-Kotlin
private var mockParent = mock<ViewGroup>()
Better Mocking with Mockito-Kotlin
// private var mockParent = mock<ViewGroup>()
private var mockParent: ViewGroup = mock {
on { childCount } doReturn 0
}
Better Mocking with Mockito-Kotlin
@Test fun `Should return null if called with invalid position`() {
whenever(mockParent.childCount) doReturn 0
assertThat(docs.getViewAtPosition(0)).isNull()
}
How Does It Work?
inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java)
Better Assertions with Kluent
@Test fun `Should return null if called with invalid position`() {
whenever(mockParent.childCount) doReturn 0
docs.getViewAtPosition(0) `should be` null
}
How Does It Work?
import org.junit.Assert.*
infix fun Any?.`should be`(theOther: Any?) = assertSame(theOther, this)
infix fun Any?.shouldBe(theOther: Any?) = this `should be` theOther
Other Goodies
Multiline Strings
val json =
"""
{
"name": "Bob",
"age": 57
}
"""
@Test fun `Should parse JSON correctly`() {
gson.fromJson(json, Person::class.java) `should equal` Person("Bob", 57)
}
“with” for Multiple Assertions
@Test fun `Should parse JSON correctly #2`() {
val person = gson.fromJson(json, Person::class.java)
with(person) {
name `should equal` "Bob"
age `should equal` 57
}
}
Factory Functions with Named Args
public class Person {
private String name;
private int age;
private boolean isAKotlinProgrammer;
public Person(String name, int age, boolean isAKotlinProgrammer) {
this.name = name;
this.age = age;
this.isAKotlinProgrammer = isAKotlinProgrammer;
}
…
}
Factory Functions with Named Args
fun person(
name: String = "",
age: Int = 0,
isAKotlinProgrammer: Boolean = false) =
Person(name, age, isAKotlinProgrammer)
@Test fun `Should ...`() {
val person = person(name = "Bob", age = 57)
...
}
@JvmOverloads
@JvmOverloads
fun person(
name: String = "",
age: Int = 0,
isAKotlinProgrammer: Boolean = false) =
Person(name, age, isAKotlinProgrammer)
...and more magic in store!
Thanks!
Egor Andreevici
Software Developer @ 1&1
@EgorAnd
Ad

More Related Content

What's hot (20)

Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
Rody Middelkoop
 
Unit Testing in Android
Unit Testing in AndroidUnit Testing in Android
Unit Testing in Android
Md Shamsul Arafin Mahtab
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
Giuseppe Arici
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS app
Aleks Zinevych
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Android Fragment
Android FragmentAndroid Fragment
Android Fragment
Kan-Han (John) Lu
 
Introduction to android testing
Introduction to android testingIntroduction to android testing
Introduction to android testing
Diego Torres Milano
 
Android Services
Android ServicesAndroid Services
Android Services
Ahsanul Karim
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
Sunil OS
 
Unit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdfUnit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdf
Katy Slemon
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
Phat VU
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Edureka!
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
priya_trivedi
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
priya_trivedi
 
Jest
JestJest
Jest
Lucas Lira Gomes
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Scott Leberknight
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
Prawesh Shrestha
 
API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)
Peter Thomas
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
amaankhan
 
Android async task
Android async taskAndroid async task
Android async task
Madhu Venkat
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
Rody Middelkoop
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
Giuseppe Arici
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS app
Aleks Zinevych
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Unit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdfUnit Testing Using Mockito in Android (1).pdf
Unit Testing Using Mockito in Android (1).pdf
Katy Slemon
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
Phat VU
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Edureka!
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
Prawesh Shrestha
 
API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)
Peter Thomas
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
amaankhan
 
Android async task
Android async taskAndroid async task
Android async task
Madhu Venkat
 

Similar to Unit Testing in Kotlin (20)

Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
Minseo Chayabanjonglerd
 
Practical tips for building apps with kotlin
Practical tips for building apps with kotlinPractical tips for building apps with kotlin
Practical tips for building apps with kotlin
Adit Lal
 
Save time with kotlin in android development
Save time with kotlin in android developmentSave time with kotlin in android development
Save time with kotlin in android development
Adit Lal
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with Kotlin
Brandon Wever
 
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android ExtensionsReducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Patrick Steiger
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
Kurt Renzo Acosta
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
MobileAcademy
 
Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019 Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019
Sriyank Siddhartha
 
droidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutinesdroidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutines
Arthur Nagy
 
Realm or: How I learned to stop worrying and love my app database
Realm or: How I learned to stop worrying and love my app databaseRealm or: How I learned to stop worrying and love my app database
Realm or: How I learned to stop worrying and love my app database
Sergi Martínez
 
Functional Core, Reactive Shell
Functional Core, Reactive ShellFunctional Core, Reactive Shell
Functional Core, Reactive Shell
Giovanni Lodi
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
Matthew Clarke
 
Unit testing powershell
Unit testing powershellUnit testing powershell
Unit testing powershell
Matt Wrock
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
Yevhen Bobrov
 
つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~
kamedon39
 
Kotlin wonderland
Kotlin wonderlandKotlin wonderland
Kotlin wonderland
Jedsada Tiwongvokul
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
Kurt Renzo Acosta
 
TDAD
TDADTDAD
TDAD
Daniele Bottillo
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
Schalk Cronjé
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
Christian Melchior
 
Practical tips for building apps with kotlin
Practical tips for building apps with kotlinPractical tips for building apps with kotlin
Practical tips for building apps with kotlin
Adit Lal
 
Save time with kotlin in android development
Save time with kotlin in android developmentSave time with kotlin in android development
Save time with kotlin in android development
Adit Lal
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with Kotlin
Brandon Wever
 
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android ExtensionsReducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Patrick Steiger
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
MobileAcademy
 
Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019 Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019
Sriyank Siddhartha
 
droidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutinesdroidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutines
Arthur Nagy
 
Realm or: How I learned to stop worrying and love my app database
Realm or: How I learned to stop worrying and love my app databaseRealm or: How I learned to stop worrying and love my app database
Realm or: How I learned to stop worrying and love my app database
Sergi Martínez
 
Functional Core, Reactive Shell
Functional Core, Reactive ShellFunctional Core, Reactive Shell
Functional Core, Reactive Shell
Giovanni Lodi
 
Unit testing powershell
Unit testing powershellUnit testing powershell
Unit testing powershell
Matt Wrock
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
Yevhen Bobrov
 
つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~
kamedon39
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
Kurt Renzo Acosta
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
Schalk Cronjé
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
Christian Melchior
 
Ad

Recently uploaded (20)

Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Ad

Unit Testing in Kotlin

  • 1. Unit Testing in Kotlin Egor Andreevici Software Developer @ 1&1 @EgorAnd
  • 2. Android: In The Java Zone
  • 3. Java Kotlin + Official + Stable - Old - Verbose + Modern + Expressive - Stable? - Support?
  • 4. Starting with Kotlin on Android? Start small! Start with unit tests!
  • 6. Benefits of Unit Tests Provide a safety net around your code Document your code… what? Promote good design practices
  • 7. Bad Documentation /** * Get a subview of the root view at a certain position. * * @param position Position, 0 <= position < root child count * @return Subview at given position, or {@code null} if position is out of * bounds */ public View getViewAtPosition(int position) { if (position >= 0 && position < root.getChildCount()) { return root.getChildAt(position); } return null; }
  • 8. Bad Documentation /** * Get a subview of the root view at a certain position. * * @param position Position, 0 <= position < root child count * @return Subview at given position, or {@code null} if position is out of * bounds */ public View getViewAtPosition(int position) { if (position >= 0 && position < root.getChildCount()) { return root.getChildAt(position); } throw new IndexOutOfBoundsException("Invalid position " + position); }
  • 9. A Better Test @Test public void shouldReturnNullIfCalledWithInvalidPosition() { doReturn(0).when(mockParent).getChildCount(); assertThat(docs.getViewAtPosition(0)).isNull(); }
  • 11. Kotlinize @Test fun shouldReturnNullIfCalledWithInvalidPosition() { doReturn(0).`when`<ViewGroup>(mockParent).childCount assertThat(docs.getViewAtPosition(0)).isNull() }
  • 12. Better Method Names @Test fun `Should return null if called with invalid position`() { doReturn(0).`when`<ViewGroup>(mockParent).childCount assertThat(docs.getViewAtPosition(0)).isNull() }
  • 13. Better Mocking with Mockito-Kotlin ● Reified types for mock creation ● Fluent method mocking syntax ● More niceties
  • 14. Better Mocking with Mockito-Kotlin private var mockParent = mock<ViewGroup>()
  • 15. Better Mocking with Mockito-Kotlin // private var mockParent = mock<ViewGroup>() private var mockParent: ViewGroup = mock { on { childCount } doReturn 0 }
  • 16. Better Mocking with Mockito-Kotlin @Test fun `Should return null if called with invalid position`() { whenever(mockParent.childCount) doReturn 0 assertThat(docs.getViewAtPosition(0)).isNull() }
  • 17. How Does It Work? inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java)
  • 18. Better Assertions with Kluent @Test fun `Should return null if called with invalid position`() { whenever(mockParent.childCount) doReturn 0 docs.getViewAtPosition(0) `should be` null }
  • 19. How Does It Work? import org.junit.Assert.* infix fun Any?.`should be`(theOther: Any?) = assertSame(theOther, this) infix fun Any?.shouldBe(theOther: Any?) = this `should be` theOther
  • 21. Multiline Strings val json = """ { "name": "Bob", "age": 57 } """ @Test fun `Should parse JSON correctly`() { gson.fromJson(json, Person::class.java) `should equal` Person("Bob", 57) }
  • 22. “with” for Multiple Assertions @Test fun `Should parse JSON correctly #2`() { val person = gson.fromJson(json, Person::class.java) with(person) { name `should equal` "Bob" age `should equal` 57 } }
  • 23. Factory Functions with Named Args public class Person { private String name; private int age; private boolean isAKotlinProgrammer; public Person(String name, int age, boolean isAKotlinProgrammer) { this.name = name; this.age = age; this.isAKotlinProgrammer = isAKotlinProgrammer; } … }
  • 24. Factory Functions with Named Args fun person( name: String = "", age: Int = 0, isAKotlinProgrammer: Boolean = false) = Person(name, age, isAKotlinProgrammer) @Test fun `Should ...`() { val person = person(name = "Bob", age = 57) ... }
  • 25. @JvmOverloads @JvmOverloads fun person( name: String = "", age: Int = 0, isAKotlinProgrammer: Boolean = false) = Person(name, age, isAKotlinProgrammer)
  • 26. ...and more magic in store!