Skip to content

Test Double ‐ Stub

Devrath edited this page Oct 24, 2023 · 1 revision

github-header-image

Observation

  • Stub is the same as the dummy when it comes to test double
  • The difference here is that if the stub returns something we can modify it using a stub and check in the place it is being used if anything fails like any exception.
  • We check if the piece of code returns success, failure, or exception based on the block of the code.
  • If there is a piece of code inside the function that causes the exception and we need to check this we can use stubs.
  • So we use stub to check the behavior of the code under test.

Code

Cache.kt

data class Cache(val isChacheEnabled : Boolean)

LoginService.kt

interface LoginService {
    fun connectToServer()
    fun makeConnection() : Cache
    fun disconnectFromServer()
}

LoginServiceImpl.kt

open class LoginServiceImpl : LoginService {
    override fun connectToServer() { }
    override fun makeConnection(): Cache {
        if(someCustomImplementation()){
            return Cache(isChacheEnabled = true)
        }
        else{
            return Cache(isChacheEnabled = false)
        }
    }

    override fun disconnectFromServer() { }

    private fun someCustomImplementation(): Boolean {
        // Some implementation logic
        return true;
    }
}

LoginServiceImplDummy.kt

class LoginServiceImplDummy : LoginServiceImpl() {
    override fun connectToServer() {
        super.connectToServer()
    }
    override fun makeConnection(): Cache {
        super.makeConnection()
        return Cache(isChacheEnabled = false)
    }
    override fun disconnectFromServer() {
        super.disconnectFromServer()
    }
}