Kotlinでテストコードを書く

316 views
302 views

Published on

第3回kotlin勉強会 @ SanSan

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
316
On SlideShare
0
From Embeds
0
Number of Embeds
48
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Kotlinでテストコードを書く

  1. 1. 
 

  2. 2. 
 

  3. 3. android { sourceSets {
 main.java.srcDirs += 'src/main/kotlin'
 test.java.srcDirs += 'src/test/kotlin'
 androidTest.java.srcDirs += 'src/androidTest/kotlin'
 }
 }
  4. 4. //ExampleUnitTest.java public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
  5. 5. //ExampleUnitTest.kt class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
  6. 6. //app/build.gradle dependencies { testCompile 'org.mockito:mockito-core:1.10.19' }
  7. 7. //KotlinSimpleMockitoTest.kt class KotlinSimpleMockitoTest { @Test fun Context () { val context = Mockito.mock(Context::class.java) Mockito.`when`(context.packageName).thenReturn("shoma2da") val packageName = context.getPackageName(); Assert.assertEquals("shoma2da", packageName); } }
  8. 8. //User.kt class User(val birthYear:Int) { fun getAge() = 2016 - birthYear }
  9. 9. //UserTest.kt class UserTest { @Test fun User () { val user = Mockito.mock(User::class.java) Mockito.`when`(user.getAge()).thenReturn(1) val age = user.getAge() Assert.assertEquals(1, age) } }
  10. 10. //logcat org.mockito.exceptions.base.MockitoException: Cannot mock/spy class YOUR_PACKAGE.User Mockito cannot mock/spy following: - final classes - anonymous classes - primitive types
  11. 11. open 

  12. 12. //User.kt open class User(val birthYear:Int) { open fun getAge() = 2016 - birthYear }
  13. 13. //User.kt interface User { fun getAge():Int } class UserImpl(val birthYear:Int) : User { override fun getAge() = 2016 - birthYear }
  14. 14. //UserTest.kt @RunWith(PowerMockRunner::class) @PrepareForTest(User::class) class UserTest { @Test fun User () { val user = PowerMockito.mock(User::class.java) Mockito.`when`(user.getAge()).thenReturn(1) val age = user.getAge() Assert.assertEquals(1, age) } } //build.gradle dependencies { testCompile 'org.powermock:powermock-module-junit4:1.6.2'
 testCompile 'org.powermock:powermock-api-mockito:1.6.2' }
  15. 15. 
 


×