Sobes.tech
Middle

Kotlin kodunu test etmek için hangi test yöntemlerini kullanıyorsunuz?

sobes.tech yapay zeka

AI'dan gelen yanıt

Aşağıdaki test yöntemlerini uyguluyorum:

  • Birim testi: Bağımsız olarak küçük bileşenlerin (fonksiyonlar, sınıflar) kontrolü. JUnit 5 veya Spek kullanıyorum.
  • Entegrasyon testi: Birden fazla bileşen veya alt sistem arasındaki etkileşimin kontrolü.
  • UI testi: Gerçek cihaz veya emülatörde kullanıcı arayüzünün testi. Android için Espresso veya UI Automator kullanıyorum.
  • Enstrümantal test: Bir cihaz veya emülatörde çalıştırılması gereken test. UI ve bazı entegrasyon testlerini içerir.
  • Uçtan uca (End-to-End) testi: Kullanıcının yaptığı eylemleri taklit ederek tüm uygulamanın baştan sona testi.

Testleri yazarken, bağımlılıkları taklit etmek için Mockito veya MockK, doğrulama ifadeleri yazmak için Hamcrest veya AssertJ kullanıyorum.

// JUnit 5 ve MockK kullanarak bir Birim Testi örneği
import io.mockk.every
import io.mockk.mockk
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test

class MyServiceTest {

    @Test
    fun `calculateSum doğru toplamı döndürmeli`() {
        // Bağımlılığı taklit et
        val dependency: Dependency = mockk()
        every { dependency.getValue() } returns 10

        val service = MyService(dependency)
        val result = service.calculateSum(20)

        // Sonucu kontrol et
        assertEquals(30, result)
    }
}

class MyService(private val dependency: Dependency) {
    fun calculateSum(a: Int): Int {
        return a + dependency.getValue()
    }
}

interface Dependency {
    fun getValue(): Int
}
// Espresso kullanarak Android için UI testi örneği
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
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 org.junit.Rule
import org.junit.Test

class MainActivityTest {

    @get:Rule
    var activityRule: ActivityScenarioRule<MainActivity> = ActivityScenarioRule(MainActivity::class.java)

    @Test
    fun butona tıklama metni değiştiriyor() {
        // ID ile butonu bul ve tıkla
        onView(withId(R.id.button)).perform(click())

        // TextView'daki metnin değiştiğini kontrol et
        onView(withId(R.id.textView)).check(matches(withText("Metin değişti!")))
    }
}