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

More Related Content

What's hot

A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
XPeppers
 
Kotlin Language powerpoint show file
Kotlin Language powerpoint show fileKotlin Language powerpoint show file
Kotlin Language powerpoint show file
Saurabh Tripathi
 
Kotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenesKotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenes
Anh Vu
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
Shai Yallin
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
Sam Brannen
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
Kirill Rozov
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
Ramon Ribeiro Rabello
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
Abner Chih Yi Huang
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
Rody Middelkoop
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
Hawkman Academy
 
Demystifying Angular Animations
Demystifying Angular AnimationsDemystifying Angular Animations
Demystifying Angular Animations
Gil Fink
 
Testing with Express, Mocha & Chai
Testing with Express, Mocha & ChaiTesting with Express, Mocha & Chai
Testing with Express, Mocha & Chai
Joerg Henning
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
Dariusz Lorenc
 
Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
Syed Awais Mazhar Bukhari
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
Kotlin vs Java | Edureka
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | Edureka
Edureka!
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
Kurt Renzo Acosta
 

What's hot (20)

A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Kotlin Language powerpoint show file
Kotlin Language powerpoint show fileKotlin Language powerpoint show file
Kotlin Language powerpoint show file
 
Kotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenesKotlin coroutine - behind the scenes
Kotlin coroutine - behind the scenes
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
C#.NET
C#.NETC#.NET
C#.NET
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Demystifying Angular Animations
Demystifying Angular AnimationsDemystifying Angular Animations
Demystifying Angular Animations
 
Testing with Express, Mocha & Chai
Testing with Express, Mocha & ChaiTesting with Express, Mocha & Chai
Testing with Express, Mocha & Chai
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Kotlin vs Java | Edureka
Kotlin vs Java | EdurekaKotlin vs Java | Edureka
Kotlin vs Java | Edureka
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
 

Similar to Unit Testing in Kotlin

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 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 powershellMatt 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
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
 
Kotlin After 9 Months
Kotlin After 9 MonthsKotlin After 9 Months
Kotlin After 9 Months
Thiago “Fred” Porciúncula
 

Similar to Unit Testing in Kotlin (20)

Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
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
 
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
 
Be More Productive with Kotlin
Be More Productive with KotlinBe More Productive with Kotlin
Be More Productive with Kotlin
 
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
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019 Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019
 
droidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutinesdroidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutines
 
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
 
Functional Core, Reactive Shell
Functional Core, Reactive ShellFunctional Core, Reactive Shell
Functional Core, Reactive Shell
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
 
Unit testing powershell
Unit testing powershellUnit testing powershell
Unit testing powershell
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~
 
Kotlin wonderland
Kotlin wonderlandKotlin wonderland
Kotlin wonderland
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
TDAD
TDADTDAD
TDAD
 
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
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
Kotlin After 9 Months
Kotlin After 9 MonthsKotlin After 9 Months
Kotlin After 9 Months
 

Recently uploaded

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
QuickwayInfoSystems3
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 

Recently uploaded (20)

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 

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!