A discovery over the different ways of testing in kotlin. Will go through Spek, HamKrest and Mockito. How to set it all up, how to do different kind of tests (intrumentation and unit).
“You should create instrumented unit tests if your tests need access to instrumentation information (such as the target app’s context) or if they require the real implementation of an Android framework component (such as a Parcelable or SharedPreferences obj ect).”
“You should create instrumented unit tests if your tests need access to instrumentation information (such as the target app’s context) or if they require the real implementation of an Android framework component (such as a Parcelable or SharedPreferences obj ect).”
- Databases - Real Permissions - Build version specific on device - Black box testing - Learning @RunWith(AndroidJUnit4::class) @SmallTest class InstrumentedExampleTest { @Test fun use_app_context() { val appContext = InstrumentationRegistry.getTargetContext() assertEquals(“se.accepted.test”, appContext.packageName) } }
HamkrestUnitTest { @Test fun startsWith() { val hasOnlyOneColon = Matcher(String::singleChar,’:’) val uri = "https://accepted.se" assert.that(uri, startsWith(“https") and hasOnlyOneColon) } } fun String.singleChar(c:Char):Boolean = count{ it == c } == 1
Mock everything @RunWith(MockitoJUnitRunner::class) class MockitoUnitTest { @Test fun inlineMocking() { val text = mock<TextView> { on { text } doReturn “text” on { elevation } doReturn 0.4f } val reverser = TextReverser(text) assert.that(reverser.text, equalTo("text".reversed())) } }
it class ExampleSpek : Spek({ describe(“a stream from a channel”) { val stream = Channel("http://stream.dash").asStream() it(“is not null”){ assertThat(stream, anything) } it(“has an uri”){ assertThat(stream.uri, !isEmptyString) } it(“has a query”){ assertThat(stream.uri, containsSubstring(“?")) } } })