Day45 of #100DaysOfCode

#CodeTogether Day 45/100

Unit 2: Layouts

What is the difference between Unit and Instrumentation Tests

Often Unit tests are referred to as “local tests” or “local unit tests”. The main reason for this seems to be that we want to be able to run tests without a device or an emulator attached.

Unit tests cannot test the UI for our app without mocking objects such as an Activity.

Instrumentation tests run on a device or an emulator. In the background, our app will be installed and then a testing app will also be installed which will control our app, launch it, and run UI tests as needed.

Instrumentation tests can be used to test none UI logic as well. They are especially useful when we need to test code that has a dependency on a context.

package com.example.tiptimeclass CalculatorTests {
}
@RunWith(AndroidJUnit4::class)
class CalculatorTests {
}
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.runner.RunWith
@get:Rule() 
val activity = ActivityScenarioRule(MainActivity::class.java)
@Test
fun calculate_20_percent_tip() {
}

We will use Espresso for the instrumentation tests. It is a library that let us interact with the UI components through our code.

package com.example.tiptime

import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.hamcrest.Matchers.containsString
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class CalculatorTests {

@get:Rule()
val activity = ActivityScenarioRule(MainActivity::class.java)

@Test
fun calculate_default_tip() {
onView(withId(R.id.cost_of_service_edit_text))
.perform(typeText("50.00"))

onView(withId(R.id.calculate_button)).perform(click())

onView(withId(R.id.tip_result))
.check(matches(withText(containsString("10.00"))))
}
}

Today I Learned:

That is all for Day45 ✅

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store