Slide 1

Slide 1 text

No content

Slide 2

Slide 2 text

Stuart Kent @skentphd

Slide 3

Slide 3 text

Detroit Labs @detroitlabs

Slide 4

Slide 4 text

Unit Testing Trends

Slide 5

Slide 5 text

2014 Fat Activities Robolectric unit tests ☹

Slide 6

Slide 6 text

2015 MVP/MVVM JUnit unit tests closer !

Slide 7

Slide 7 text

2016 "Dagger by default" JUnit unit tests for all! ! ... &

Slide 8

Slide 8 text

2019 ! Dagger vs Koin Renewed focus on actual DI needs More interest in simple DI solutions

Slide 9

Slide 9 text

This Talk Unit test driven dependency injection Simple method; not scary ⚖ Advantages, limitations, options

Slide 10

Slide 10 text

Takeaways Manual dependency injection is viable Practical recipe Courage to critically evaluate tools & opinions

Slide 11

Slide 11 text

Kotlin

Slide 12

Slide 12 text

This code works great in production. class HumanTimeHelper { // Consumer fun getTimeOfDay(): String { return when (LocalTime.now().hour) { // Dependency in 6..12 -> "Morning" in 13..17 -> "Afternoon" in 18..21 -> "Evening" else -> "Night" } } }

Slide 13

Slide 13 text

This code works great in production. class HumanTimeHelper { // Consumer fun getTimeOfDay(): String { return when (LocalTime.now().hour) { // Dependency in 6..12 -> "Morning" in 13..17 -> "Afternoon" in 18..21 -> "Evening" else -> "Night" } } }

Slide 14

Slide 14 text

This code works great in production. class HumanTimeHelper { // Consumer fun getTimeOfDay(): String { return when (LocalTime.now().hour) { // Dependency in 6..12 -> "Morning" in 13..17 -> "Afternoon" in 18..21 -> "Evening" else -> "Night" } } }

Slide 15

Slide 15 text

This code works great in production. class HumanTimeHelper { // Consumer fun getTimeOfDay(): String { return when (LocalTime.now().hour) { // Dependency in 6..12 -> "Morning" in 13..17 -> "Afternoon" in 18..21 -> "Evening" else -> "Night" } } }

Slide 16

Slide 16 text

Unit testing HumanTimeHelper is... impossible? @Test fun testGetTimeOfDayMorning() { val humanTimeHelper = HumanTimeHelper() val expected = "Morning" val actual = humanTimeHelper.getTimeOfDay() // Will fail ~70% of the time! assertEquals(expected, actual) }

Slide 17

Slide 17 text

Our consumer (HumanTimeHelper) is tightly coupled to its dependency (LocalTime.now()). class HumanTimeHelper { fun getTimeOfDay(): String { return when (LocalTime.now().hour) { in 6..12 -> "Morning" in 13..17 -> "Afternoon" in 18..21 -> "Evening" else -> "Night" } } }

Slide 18

Slide 18 text

Goals Specify a fake time in unit tests Continue to use the real time in production

Slide 19

Slide 19 text

Goals Specify a fake X in unit tests Continue to use the real X in production

Slide 20

Slide 20 text

Step 1: define an interface that describes the ideal behavior of the dependency from the point of view of the consumer. interface IClock { fun hour(): Int }

Slide 21

Slide 21 text

Step 2: inject an instance of the new interface into the consumer via its constructor(s), and save it as a property. class HumanTimeHelper(private val clock: IClock) { fun getTimeOfDay(): String { return when (LocalTime.now().hour) { in 6..12 -> "Morning" in 13..17 -> "Afternoon" in 18..21 -> "Evening" else -> "Night" } } }

Slide 22

Slide 22 text

Step 3: replace the tightly-coupled dependency with the newly- injected instance throughout the consumer's code. class HumanTimeHelper(private val clock: IClock) { fun getTimeOfDay(): String { return when (clock.hour()) { in 6..12 -> "Morning" in 13..17 -> "Afternoon" in 18..21 -> "Evening" else -> "Night" } } }

Slide 23

Slide 23 text

Step 4: create a production implementation of the new interface that mimics original behavior. class SystemClock : IClock { override fun hour() = LocalTime.now().hour }

Slide 24

Slide 24 text

Step 4: create a production implementation of the new interface that mimics original behavior. class SystemClock : IClock { override fun hour() = LocalTime.now().hour }

Slide 25

Slide 25 text

Step 5: update all consumer constructor calls in production code, passing in the production implementation. val humanTimeHelper = HumanTimeHelper(SystemClock())

Slide 26

Slide 26 text

Step 6: update all consumer constructor calls in test code, passing in a mock implementation with deterministic behavior. @Test fun testGetTimeOfDayMorning() { val humanTimeHelper = HumanTimeHelper(object : IClock { override fun hour() = 6 }) val expected = "Morning" val actual = humanTimeHelper.getTimeOfDay() // Will pass 100% of the time! assertEquals(expected, actual) }

Slide 27

Slide 27 text

Step 6: update all consumer constructor calls in test code, passing in a mock implementation with deterministic behavior. @Test fun testGetTimeOfDayMorning() { val humanTimeHelper = HumanTimeHelper(object : IClock { override fun hour() = 6 }) val expected = "Morning" val actual = humanTimeHelper.getTimeOfDay() // Will pass 100% of the time! assertEquals(expected, actual) }

Slide 28

Slide 28 text

Step 6: update all consumer constructor calls in test code, passing in a mock implementation with deterministic behavior. @Test fun testGetTimeOfDayEvening() { val humanTimeHelper = HumanTimeHelper(object : IClock { override fun hour() = 19 }) val expected = "Evening" val actual = humanTimeHelper.getTimeOfDay() // Will pass 100% of the time! assertEquals(expected, actual) }

Slide 29

Slide 29 text

Recipe Recap

Slide 30

Slide 30 text

Recipe Recap 1. Create ideal interface.

Slide 31

Slide 31 text

Recipe Recap 1. Create ideal interface. 2. Inject interface into constructor.

Slide 32

Slide 32 text

Recipe Recap 1. Create ideal interface. 2. Inject interface into constructor. 3. Use injected interface.

Slide 33

Slide 33 text

Recipe Recap 1. Create ideal interface. 2. Inject interface into constructor. 3. Use injected interface. 4. Create real implementation.

Slide 34

Slide 34 text

Recipe Recap 1. Create ideal interface. 2. Inject interface into constructor. 3. Use injected interface. 4. Create real implementation. 5. Pass real implementation in production.

Slide 35

Slide 35 text

Recipe Recap 1. Create ideal interface. 2. Inject interface into constructor. 3. Use injected interface. 4. Create real implementation. 5. Pass real implementation in production. 6. Pass mock implementation in tests.

Slide 36

Slide 36 text

Android

Slide 37

Slide 37 text

Android MVP We've dealt with a dependency affected by time. Next we'll practice our recipe with dependencies affected by: • network conditions • local storage state We'll start with MVP as it's slightly simpler.

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

class CreditCardPresenter(private val view: ICreditCardsView, context: Context) { private val prefs = context.getSharedPreferences("creditCard", MODE_PRIVATE) fun onCardSelected(card: CreditCard) { prefs.edit().putInt("lastCardId", card.id).apply() view.advance() } fun refreshCards() { val lastCardId = prefs.getInt("lastCardId", -1) RestApi() .fetchUserCards() .flatMapIterable { it } .map { it.copy(favorite = (it.id == lastCardId)) } .toList() .subscribe(Consumer { view.display(it) }) } }

Slide 40

Slide 40 text

class CreditCardPresenter(private val view: ICreditCardsView, context: Context) { private val prefs = context.getSharedPreferences("creditCard", MODE_PRIVATE) fun onCardSelected(card: CreditCard) { prefs.edit().putInt("lastCardId", card.id).apply() view.advance() } fun refreshCards() { val lastCardId = prefs.getInt("lastCardId", -1) RestApi() .fetchUserCards() .flatMapIterable { it } .map { it.copy(favorite = (it.id == lastCardId)) } .toList() .subscribe(Consumer { view.display(it) }) } }

Slide 41

Slide 41 text

class CreditCardPresenter(private val view: ICreditCardsView, context: Context) { private val prefs = context.getSharedPreferences("creditCard", MODE_PRIVATE) fun onCardSelected(card: CreditCard) { prefs.edit().putInt("lastCardId", card.id).apply() view.advance() } fun refreshCards() { val lastCardId = prefs.getInt("lastCardId", -1) RestApi() .fetchUserCards() .flatMapIterable { it } .map { it.copy(favorite = (it.id == lastCardId)) } .toList() .subscribe(Consumer { view.display(it) }) } }

Slide 42

Slide 42 text

class CreditCardPresenter(private val view: ICreditCardsView, context: Context) { private val prefs = context.getSharedPreferences("creditCard", MODE_PRIVATE) fun onCardSelected(card: CreditCard) { prefs.edit().putInt("lastCardId", card.id).apply() view.advance() } fun refreshCards() { val lastCardId = prefs.getInt("lastCardId", -1) RestApi() .fetchUserCards() .flatMapIterable { it } .map { it.copy(favorite = (it.id == lastCardId)) } .toList() .subscribe(Consumer { view.display(it) }) } }

Slide 43

Slide 43 text

class CreditCardsActivity : AppCompatActivity(), ICreditCardsView { private lateinit var presenter: CreditCardPresenter override fun onCreate(savedInstanceState: Bundle?) { // ... presenter = CreditCardPresenter(this, this) } // ... }

Slide 44

Slide 44 text

class CreditCardPresenter(private val view: ICreditCardsView, context: Context) { private val prefs = context.getSharedPreferences("creditCard", MODE_PRIVATE) fun onCardSelected(card: CreditCard) { prefs.edit().putInt("lastCardId", card.id).apply() view.advance() } fun refreshCards() { val lastCardId = prefs.getInt("lastCardId", -1) RestApi() .fetchUserCards() .flatMapIterable { it } .map { it.copy(favorite = (it.id == lastCardId)) } .toList() .subscribe(Consumer { view.display(it) }) } }

Slide 45

Slide 45 text

Step 1: Create ideal interface. interface IUserCardsFetcher { fun fetchUserCards(): Observable> }

Slide 46

Slide 46 text

Step 2: Inject interface into constructor. class CreditCardPresenter( private val view: ICreditCardsView, private val userCardsFetcher: IUserCardsFetcher, context: Context ) { // ... }

Slide 47

Slide 47 text

Step 3: Use injected interface. fun refreshCards() { val lastCardId = prefs.getInt("lastCardId", -1) userCardsFetcher .fetchUserCards() .flatMapIterable { it } .map { it.copy(favorite = (it.id == lastCardId)) } .toList() .subscribe(Consumer { view.display(it) }) }

Slide 48

Slide 48 text

Step 4: Create Update real implementation. class RestApi : IUserCardsFetcher { // ... override fun fetchUserCards(): Observable> { // ... } // ... }

Slide 49

Slide 49 text

Step 5: Pass real implementation in production. class CreditCardsActivity : AppCompatActivity(), ICreditCardsView { private lateinit var presenter: CreditCardPresenter override fun onCreate(savedInstanceState: Bundle?) { // ... presenter = CreditCardPresenter(this, RestApi(), this) } // ... }

Slide 50

Slide 50 text

Step 6: Pass mock implementation in tests. ⚠ We're not ready to test yet; both presenter methods still use a hard-coded dependency!

Slide 51

Slide 51 text

class CreditCardPresenter( // ... context: Context ) { private val prefs = context.getSharedPreferences("creditCard", MODE_PRIVATE) fun onCardSelected(card: CreditCard) { prefs.edit().putInt("lastCardId", card.id).apply() // ... } fun refreshCards() { val lastCardId = prefs.getInt("lastCardId", -1) // ... } }

Slide 52

Slide 52 text

Step 1: Create ideal interface. interface ILastCardStorage { fun getLastCardId(): Int? fun saveLastCardId(id: Int) }

Slide 53

Slide 53 text

Step 2: Inject interface into constructor and remove injected Context. class CreditCardPresenter( private val view: ICreditCardsView, private val userCardsFetcher: IUserCardsFetcher, private val lastCardStorage: ILastCardStorage ) { // ... }

Slide 54

Slide 54 text

Step 3: Use injected interface and remove SharedPreferences property. fun onCardSelected(card: CreditCard) { lastCardStorage.saveLastCardId(card.id) view.advance() } fun refreshCards() { val lastCardId = lastCardStorage.getLastCardId() // ... }

Slide 55

Slide 55 text

Step 4: Create real implementation. class PrefsLastCardStorage(context: Context) : ILastCardStorage { private val prefs = context.getSharedPreferences("creditCard", MODE_PRIVATE) override fun getLastCardId(): Int? { val lastCardId = prefs.getInt("lastCardId", -1) return if (lastCardId >= 0) lastCardId else null } override fun saveLastCardId(id: Int) { prefs.edit().putInt("lastCardId", id).apply() } }

Slide 56

Slide 56 text

Step 4: Create real implementation. class PrefsLastCardStorage(context: Context) : ILastCardStorage { private val prefs = context.getSharedPreferences("creditCard", MODE_PRIVATE) override fun getLastCardId(): Int? { val lastCardId = prefs.getInt("lastCardId", -1) return if (lastCardId >= 0) lastCardId else null } override fun saveLastCardId(id: Int) { prefs.edit().putInt("lastCardId", id).apply() } }

Slide 57

Slide 57 text

Step 5: Pass real implementation in production. class CreditCardsActivity : AppCompatActivity(), ICreditCardsView { private lateinit var presenter: CreditCardPresenter override fun onCreate(savedInstanceState: Bundle?) { // ... presenter = CreditCardPresenter( this, RestApi(), PrefsLastCardStorage(this) ) } // ... }

Slide 58

Slide 58 text

Step 6: Pass mock implementations in tests. @Test fun `correct card marked favorite`() { whenever(mockFetcher.fetchUserCards()).thenReturn( Observable.just(listOf( CreditCard(id = 1, lastFour = "1234", favorite = false), CreditCard(id = 2, lastFour = "7529", favorite = false) )) ) whenever(mockStorage.getLastCardId()).thenReturn(2) val presenter = CreditCardPresenter(mockView, mockFetcher, mockStorage) presenter.refreshCards() verify(mockView).display(cardsCaptor.capture()) val favoriteIds = cardsCaptor.firstValue.filter(CreditCard::favorite) assertEquals(favoriteIds.size, 1) assertEquals(favoriteIds.first().id, 2) }

Slide 59

Slide 59 text

Step 6: Pass mock implementations in tests. @Test fun `correct card marked favorite`() { whenever(mockFetcher.fetchUserCards()).thenReturn( Observable.just(listOf( CreditCard(id = 1, lastFour = "1234", favorite = false), CreditCard(id = 2, lastFour = "7529", favorite = false) )) ) whenever(mockStorage.getLastCardId()).thenReturn(2) val presenter = CreditCardPresenter(mockView, mockFetcher, mockStorage) presenter.refreshCards() verify(mockView).display(cardsCaptor.capture()) val favoriteIds = cardsCaptor.firstValue.filter(CreditCard::favorite) assertEquals(favoriteIds.size, 1) assertEquals(favoriteIds.first().id, 2) }

Slide 60

Slide 60 text

Step 6: Pass mock implementations in tests. @Test fun `correct card marked favorite`() { whenever(mockFetcher.fetchUserCards()).thenReturn( Observable.just(listOf( CreditCard(id = 1, lastFour = "1234", favorite = false), CreditCard(id = 2, lastFour = "7529", favorite = false) )) ) whenever(mockStorage.getLastCardId()).thenReturn(2) val presenter = CreditCardPresenter(mockView, mockFetcher, mockStorage) presenter.refreshCards() verify(mockView).display(cardsCaptor.capture()) val favoriteIds = cardsCaptor.firstValue.filter(CreditCard::favorite) assertEquals(favoriteIds.size, 1) assertEquals(favoriteIds.first().id, 2) }

Slide 61

Slide 61 text

Step 6: Pass mock implementations in tests. @Test fun `correct card marked favorite`() { whenever(mockFetcher.fetchUserCards()).thenReturn( Observable.just(listOf( CreditCard(id = 1, lastFour = "1234", favorite = false), CreditCard(id = 2, lastFour = "7529", favorite = false) )) ) whenever(mockStorage.getLastCardId()).thenReturn(2) val presenter = CreditCardPresenter(mockView, mockFetcher, mockStorage) presenter.refreshCards() verify(mockView).display(cardsCaptor.capture()) val favoriteIds = cardsCaptor.firstValue.filter(CreditCard::favorite) assertEquals(favoriteIds.size, 1) assertEquals(favoriteIds.first().id, 2) }

Slide 62

Slide 62 text

Android MVVM This recipe also works for MVVM... with tweaks! • Construction of Android view models is controlled by a ViewModelFactory. • We'll need a custom factory to inject our dependencies.

Slide 63

Slide 63 text

class CreditCardsViewModel : ViewModel() { // ... }

Slide 64

Slide 64 text

class CreditCardsActivity : AppCompatActivity() { // ... override fun onCreate(savedInstanceState: Bundle?) { // ... viewModel = ViewModelProviders.of(this) .get(CreditCardsViewModel::class.java) } }

Slide 65

Slide 65 text

class CreditCardsViewModel( private val userCardsFetcher: IUserCardsFetcher, private val lastCardStorage: ILastCardStorage ) : ViewModel() { // ... }

Slide 66

Slide 66 text

class CreditCardsVMF( private val context: Context ) : ViewModelProvider.Factory { override fun create(vm: Class): T { return CreditCardsViewModel( RestApi(), PrefsLastCardStorage(context) ) as T } }

Slide 67

Slide 67 text

class CreditCardsVMF( private val context: Context ) : ViewModelProvider.Factory { override fun create(vm: Class): T { return CreditCardsViewModel( RestApi(), PrefsLastCardStorage(context) ) as T } }

Slide 68

Slide 68 text

class CreditCardsActivity : AppCompatActivity() { // ... override fun onCreate(savedInstanceState: Bundle?) { // ... viewModel = ViewModelProviders.of(this, CreditCardsVMF(this)) .get(CreditCardsViewModel::class.java) } }

Slide 69

Slide 69 text

Recipe Strengths

Slide 70

Slide 70 text

Recipe Strengths • Very explicit.

Slide 71

Slide 71 text

Recipe Strengths • Very explicit. • Short learning curve.

Slide 72

Slide 72 text

Recipe Strengths • Very explicit. • Short learning curve. • No build or run time performance impact.

Slide 73

Slide 73 text

Recipe Strengths • Very explicit. • Short learning curve. • No build or run time performance impact. • Consumers decoupled from dependency implementations.

Slide 74

Slide 74 text

Recipe Strengths • Very explicit. • Short learning curve. • No build or run time performance impact. • Consumers decoupled from dependency implementations. • Consumers ignorant of dependency lifecycles.

Slide 75

Slide 75 text

Recipe Strengths • Very explicit. • Short learning curve. • No build or run time performance impact. • Consumers decoupled from dependency implementations. • Consumers ignorant of dependency lifecycles. • Possible to adopt incrementally.

Slide 76

Slide 76 text

Potential Recipe Weaknesses • Your needs dictate whether these are important. • Frameworks (Dagger, Koin) solve all of them, but not for free! • Let's identify and evaluate.

Slide 77

Slide 77 text

Boilerplate Explosion • Constructor injection adds code at declaration and call sites. • Evaluation: • Explicit is good. • Proximity is good. • Checked by compiler (unlike e.g. Parcelable). • Easy if each interface has 1 production implementation.

Slide 78

Slide 78 text

Interface Explosion • Consumer-centric interfaces add code & cognitive load. • Evaluation: • Solve by balancing cohesion against interface segregation principle when designing interfaces. • e.g. prefer IRestApi to IUserCardsFetcher.

Slide 79

Slide 79 text

Not DRY • No centralized control of dependency relationships. • Evaluation: • Problematic for UI tests. • Hard to swap production implementations at runtime. • Framework-free solutions exist; see "DIY Dependency Injection with Kotlin" talk by Sam Edwards.

Slide 80

Slide 80 text

Takeaways Manual dependency injection is viable Practical recipe Courage to critically evaluate tools & opinions

Slide 81

Slide 81 text

Thanks! Stuart Kent @skentphd