Share
Embed
Kodein DI & KotlinTest
Víctor González Irimia
May 29, 2018
Transcript
48 slides
-
• Dependency retrieval container • Funciona en JVM, Android, JS,
y plataformas nativas (como iOS) • Uso extensivo de inline y Kotlin DSL • Versión 5.0.0 estable Introducción a Kodein-DI -
val kodein = Kodein { bind<Random>() with singleton { Random()
} } class MyKodeinClient(private val kodein: Kodein) { private val random: Random by kodein.instance() } Un ejemplo ‘hello world’ -
val kodein = Kodein { bind<Random>() with singleton { Random()
} } class MyKodeinClient(private val kodein: Kodein) { private val random: Random by kodein.instance() } Un ejemplo básico -
val randomModule = Kodein.Module { bind<Random>() with singleton { Random()
} } fun retrofitModule(baseUrl: String) = Kodein.Module { bind<Retrofit>() with singleton { Retrofit.Builder() .baseUrl(baseUrl) .build() } } Módulos en Kodein Pueden depender unos de otros. No hay que preocuparse del orden de inicialización. -
class App : Application(), KodeinAware { override val kodein =
Kodein.lazy { import(androidModule(this@App)) import(retrofitModule(baseUrl) } } // No Android val kodein = Kodein { import(…) import(…) } Uso de módulos -
class App : Application(), KodeinAware { override val kodein =
Kodein.lazy { import(androidModule(this@App)) import(retrofitModule(baseUrl) } } // No Android val kodein = Kodein { import(…) import(…) } Uso de módulos -
• Provee todos los SystemService • Directorios de caché •
SharedPreferences • Resources y assets • ContentResolver, MainLooper, etc.. androidModule -
class MyActivity : Activity(), KodeinAware { override val kodein by
closestKodein() private val random: Random by kodein.instance() } Obtención de las dependencias • closestKodein() funciona directamente en cualquier clase Android. • Se usará closestKodein(context) para clases no Android -
val randomModule = Kodein.Module { bind<Random>() with singleton { Random()
} } val randomDirectModule = Kodein.Module { bind() from singleton { Random() } } Binding tipado vs directo -
val module = Kodein.Module { bind<Random>() with singleton { Random()
} bind<Int>("randomInt") with provider { instance<Random>().nextInt()} constant(“baseUrl") with "https://www.company.com/api" } Tagged bindings / constants -
val dataModule = Kodein.Module { bind<OkHttpClient>() with singleton { OkHttpClient.newBuilder().build()
} bind<Retrofit>() with singleton { Retrofit.Builder() .baseUrl(baseUrl) .client(instance()) .build() } } Dependencias transitivas -
val randomModule = Kodein.Module { bind<Random>() with provider { Random()
} } val retrofitModule = Kodein.Module { bind<Retrofit>() with factory { baseUrl: String -> Retrofit.Builder() .baseUrl(baseUrl) .build() } } Providers y factories -
• eagerSingleton • multiton • instance • refSingleton (softReference, weakReference,
threadLocal) Otros binders -
class MyActivity : Activity(), KodeinAware { private val _parentKodein by
closestKodein() override val kodein: Kodein = Kodein.lazy { extend(_parentKodein) bind() from provider { MainPresenter(this@MainActivity, instance(), instance(), instance()) } } val presenter: MainPresenter by instance() } Submódulos en Android -
val randomModule = Kodein.Module { bind<MainPresenter>() with scoped(androidScope<Activity>()).singleton { MainPresenter(…)
} bind<OtherPresenter>() with scoped(androidRetainedScope<Activity>()) .singleton { OtherPresenter(…) } } Scopes en Android -
• Extensión de Kodein DI: Global & ConfigurableKodein. • Permite
tener diferentes contenedores Kodein. • ConfigurableKodein permite añadir y quitar módulos dinámicamente: uso en tests. • Karumi ofrece un ejemplo en https://github.com/Karumi/ kodein-sample-testing Tests unitarios y de instrumentación -
• Ventajas frente a Dagger: • Drástica reducción de la
verbosidad. • Aprendizaje más fácil para programadores no experimentados en DI. • Inconvenientes: • Se pierde la validación en tiempo de compilación. • Mayor coste de integración en código Java. Kodein vs Dagger -
• Kodein ofrece una alternativa a Dagger, rápida y fácil
de aprender y utilizar. • Dagger sigue siendo sólido y ofrece errores en tiempo de compilación cuando hay inyecciones mal hechas. Conclusiones -
@Test fun testTransformAlbums_withValidArtists() { // When val albums = albumMapper.transform(lastFmValidAlbums)
// Then assertEquals(2, albums.size) assertEquals(lastFmValidAlbums[0].mbid, albums[0].id) assertEquals(lastFmValidAlbums[1].mbid, albums[1].id) } Motivación: tests en jUnit 4 -
@Test fun testTransformAlbums_withValidArtists() { // When val albums = albumMapper.transform(lastFmValidAlbums)
// Then assertEquals(2, albums.size) assertEquals(lastFmValidAlbums[0].mbid, albums[0].id) assertEquals(lastFmValidAlbums[1].mbid, albums[1].id) } Motivación: tests en jUnit 4 -
• Spock • Spek framework • jUnit 5 (estable desde
septiembre de 2017) Alternativas a jUnit 4 -
on("transforming two valid albums") { val albums = albumMapper.transform(lastFmValidAlbums) it("should
get an album list with two items") { assert(albums.size == 2) } it("should get expected first item in albums list") { assert(albums[0].id == lastFmValidAlbums[0].mbid) } it("should get expected second item in albums list") { assert(albums[1].id == lastFmValidAlbums[1].mbid) } } Ejemplo en Spek -
class AlbumMapperTest { @Before fun setUp() {…} @Test fun testA()
{…} @Test fun testB() {…} @Test fun testC() {…} } jUnit 4 vs Spek -
class AlbumMapperSpekTest : Spek({ given("some conditions")) { beforeEachTest {…} on(“doing
something") { // Any action it("should meet assertion A") { // An assertion } it("should meet assertion B") { // Another assertion } } } }) jUnit 4 vs Spek -
• Funciona sobre jUnit5 • Integración fácil en Android Studio
3.2 (Canary 4) • Última versión lanzada 3.1.2 Spek continúa en 1.1.5 KotlinTest -
class MyStringSpec : StringSpec({ "strings.length should return size of string"
{ "hello".length shouldBe 5 } }) class MyFunSpec : FunSpec({ test("String.length should return the length of the string") { "sammy".length shouldBe 5 "".length shouldBe 0 } }) class MyShouldSpec : ShouldSpec({ should("return the length of the string") { "sammy".length shouldBe 5 "".length shouldBe 0 } }) Specs básicos -
class AlbumMapperTest : BehaviorSpec({ given("some conditions")) { // Before all
tests When(“doing something") { // Any action Then("should meet assertion A") { // An assertion } Then(“should meet assertion B") { // Another assertion } } } }) BehaviorSpec -
class AlbumMapperTest : DescribeSpec({ describe("some conditions")) { // Before all
tests context(“doing something") { // Any action it("should meet assertion A") { // An assertion } it(“should meet assertion B") { // Another assertion } } } }) DescribeSpec -
• Como función de extensión “hello".length.shouldBe(5) • Como función infix
"hello".length shouldBe 5 Matchers -
• Lógicos (true/false) • Strings • Int, Long, Double, Float
• Colecciones y mapas • … Matchers incluidos en KotlinTest -
fun startsWithA() = object : Matcher<String> { override fun test(value:
String) = Result( value.startsWith("a"), "String $value should start with a", "String $value should not start with a” )} "abc" should startsWithA() "xyz" shouldNot startsWithA() Custom matchers -
val strings = listOf("abc", "def", "ghi") forAll(strings) { x ->
x should haveLength(3) } forAll, forNone, forOne, forAtMostOne, forAny, forExactly(n)… Inspectores -
"multiplication table" { val myTable = table( headers("a", "b", "result"),
row(9, 1, 9), row(9, 2, 18), row(9, 3, 27) ) forAll(myTable) { a, b, result -> a * b shouldBe result } } Table-driven test -
class PropertyExample: StringSpec( { "String size" { assertAll({ a: String,
b: String -> (a + b).length shouldBe a.length + b.length }) } }) • Repeticiones generadas automáticamente • 1000 por defecto Property testing -
• KotlinTest provee generadores para los tipos más comunes. •
Permite crear generadores propios: class MyIntGenerator : Gen<Int> { override fun constants() = listOf(1, 2, 3) override fun random() = generateSequence { Math.random().toInt() } } Property testing -
• Tags y grupos por tags • Tests de futuros
• Extensiones para Arrow • … Y mucho más… -
• El uso extensivo de DSL y funciones infix nos
permite aumentar la legibilidad de los tests. • jUnit 5 (y todos los frameworks basados en él) ofrecen posibilidades mucho más potentes que jUnit 4. Conclusiones