Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Melhore Seus Testes em Kotlin com Mockk
Search
Angélica Oliveira
May 29, 2019
Programming
1
280
Melhore Seus Testes em Kotlin com Mockk
Angélica Oliveira
May 29, 2019
Tweet
Share
More Decks by Angélica Oliveira
See All by Angélica Oliveira
Android in 2024: New Frontiers, Technologies, and Opportunities for Developers
angelicaoliveira
0
100
Crie Aplicativos Inteligentes para Android: Explorando a Gemini API
angelicaoliveira
0
76
Explorando as Novidades do Android: Aprimore seus Aplicativos para uma Experiência Premium
angelicaoliveira
0
86
Android 12 e suas novidades anunciadas no Google IO 2021
angelicaoliveira
1
41
Android Development, career and first steps
angelicaoliveira
0
33
A importância dos testes de UI para o desenvolvimento Android: Desde Espresso até testes para Jetpack Compose
angelicaoliveira
0
71
Como otimizar a entrega de seu aplicativo Android com App Bundle?
angelicaoliveira
0
42
Sequence x Iterable em Kotlin
angelicaoliveira
0
130
Dividir para conquistar Modularização e Features Dinâmicas no Android
angelicaoliveira
1
500
Other Decks in Programming
See All in Programming
카카오페이는 어떻게 수천만 결제를 처리할까? 우아한 결제 분산락 노하우
kakao
PRO
0
110
Outline View in SwiftUI
1024jp
1
340
OnlineTestConf: Test Automation Friend or Foe
maaretp
0
120
受け取る人から提供する人になるということ
little_rubyist
0
250
macOS でできる リアルタイム動画像処理
biacco42
9
2.4k
Tauriでネイティブアプリを作りたい
tsucchinoko
0
380
Duckdb-Wasmでローカルダッシュボードを作ってみた
nkforwork
0
130
What’s New in Compose Multiplatform - A Live Tour (droidcon London 2024)
zsmb
1
480
アジャイルを支えるテストアーキテクチャ設計/Test Architecting for Agile
goyoki
9
3.3k
Hotwire or React? ~アフタートーク・本編に含めなかった話~ / Hotwire or React? after talk
harunatsujita
1
120
距離関数を極める! / SESSIONS 2024
gam0022
0
290
flutterkaigi_2024.pdf
kyoheig3
0
160
Featured
See All Featured
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
27
4.3k
Being A Developer After 40
akosma
87
590k
The Power of CSS Pseudo Elements
geoffreycrofte
73
5.3k
Building a Modern Day E-commerce SEO Strategy
aleyda
38
6.9k
Designing the Hi-DPI Web
ddemaree
280
34k
How to train your dragon (web standard)
notwaldorf
88
5.7k
We Have a Design System, Now What?
morganepeng
50
7.2k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
191
16k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
38
1.8k
Fantastic passwords and where to find them - at NoRuKo
philnash
50
2.9k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
27
840
Six Lessons from altMBA
skipperchong
27
3.5k
Transcript
MELHORE SEUS TESTES EM KOTLIN COM MOCKK Angélica Oliveira Rafael
Toledo
MOCKS (INTRO) Mocks são uma forma de isolar o sistema
que está sendo testado dos componentes que este sistema depende. SUT: System Under Test DOC: Depended On Component
class Dependency1(val value1: Int) class Dependency2(val value2: String) class SystemUnderTest(
val dependency1: Dependency1, val dependency2: Dependency2) { fun calculate() = dependency1.value1 + dependency2.value2.toInt() } MOCKS (INTRO) Exemplo de classe em Kotlin:
@Test fun calculateAddsValues() { val doc1 = mockk<Dependency1>() val doc2
= mockk<Dependency2>() every { doc1.value1 } returns 5 every { doc2.value2 } returns "6" val sut = SystemUnderTest(doc1, doc2) assertEquals(11, sut.calculate()) } MOCKS (INTRO) Testes usando mocks como dependência:
@Test fun calculateAddsValues() { val doc1 = mockk<Dependency1>() val doc2
= mockk<Dependency2>() every { doc1.value1 } returns 5 every { doc2.value2 } returns "6" val sut = SystemUnderTest(doc1, doc2) assertEquals(11, sut.calculate()) } MOCKS (INTRO) Testes usando mocks como dependência:
@Test fun calculateAddsValues() { val doc1 = mockk<Dependency1>() val doc2
= mockk<Dependency2>() every { doc1.value1 } returns 5 every { doc2.value2 } returns "6" val sut = SystemUnderTest(doc1, doc2) assertEquals(11, sut.calculate()) } MOCKS (INTRO) Testes usando mocks como dependência:
@Test fun calculateAddsValues() { val doc1 = mockk<Dependency1>() val doc2
= mockk<Dependency2>() every { doc1.value1 } returns 5 every { doc2.value2 } returns "6" val sut = SystemUnderTest(doc1, doc2) assertEquals(11, sut.calculate()) } MOCKS (INTRO) Testes usando mocks como dependência:
• Notação nativa de Java • Problemas de nulabilidade •
Problemas com imutabilidade MOCKITO x KOTLIN
val service = Mockito.mock(Service::class.java) MOCKITO x KOTLIN
val service = Mockito.mock(Service::class.java) MOCKITO x KOTLIN
val service = Mockito.mock(Service::class.java) Mockito.`when`(service.fetchData()).thenReturn(...) MOCKITO x KOTLIN
val service = Mockito.mock(Service::class.java) Mockito.`when`(service.fetchData()).thenReturn(...) MOCKITO x KOTLIN
val service = Mockito.mock(ServiceImpl::class.java) MOCKITO x KOTLIN
val service = Mockito.mock(ServiceImpl::class.java) org.mockito.exceptions.base.MockitoException: Mockito cannot mock/spy following: com.thoughtworks.radar.ServiceImpl
– final classes – anonymous classes – primitive types MOCKITO x KOTLIN
Mockito.`when`(service).fetchUserWithId(any()) .thenReturn(mockUser) MOCKITO x KOTLIN
Mockito.`when`(service).fetchUserWithId(any()) .thenReturn(mockUser) MOCKITO x KOTLIN
Mockito.`when`(service).fetchUserWithId(any()) .thenReturn(mockUser) java.lang.NullPointerException MOCKITO x KOTLIN
MOCKK • Biblioteca para mocks em Kotlin • Possibilita escrever
testes de forma mais concisa • Features da linguagem são aproveitadas (lambdas, coroutines…)
EXEMPLOS Argument matchers: every { mock.call(more(5)) } returns 1 every
{ mock.call(or(less(5), eq(5))) } returns -1 any(), isNull(), ofType(type) Lista completa em: https://mockk.io/#matchers
EXEMPLOS Resposta esperada: every { mock1.call(5) } returnsMany listOf(1, 2,
3) every { mock1.call(5) } returns 1 andThen 2 andThen 3
EXEMPLOS Resposta esperada: every { mock1.call(5) } throws RuntimeException("error happened")
EXEMPLOS Relaxed mocks: val mock = mockk<Divider>(relaxed = true)
EXEMPLOS - MOCK DE OBJECTS object MockObj { fun add(a:
Int, b: Int) = a + b } mockkObject(MockObj) // aplica o mock ao Object assertEquals(3, MockObj.add(1, 2)) every { MockObj.add(1, 2) } returns 55 assertEquals(55, MockObj.add(1, 2))
EXEMPLOS - MOCK DE EXTENSION FUNCTIONS data class Obj(val value:
Int) // declarado no arquivo File.kt (pacote "pkg") fun Obj.extensionFunc() = value + 5 mockkStatic("pkg.FileKt") every { Obj(5).extensionFunc() } returns 11 assertEquals(11, Obj(5).extensionFunc()) verify { Obj(5).extensionFunc() }
EXEMPLOS - MOCK DE COROUTINES val car = mockk<Car>() coEvery
{ car.drive(Direction.NORTH) } returns Outcome.OK car.drive(Direction.NORTH) // returns OK coVerify { car.drive(Direction.NORTH) }
MOCKK NO ANDROID • Funciona com o uso da dependência
mockk-android • Compartilhamento entre mocks testImplementation 'io.mockk:mockk:1.9.3' androidTestImplementation 'io.mockk:mockk-android:1.9.3'
#TWTechRadar Feedbacks?
[email protected]
ou
[email protected]
OBRIGADA!