Test Driven Development for Android Kotlin

Abi Farhan
2 min readFeb 25, 2024

--

Hey guys,

In this article I am going to share about deal with Test Driven Development for Android Engineer. Let’s start it

Outlined this articles that we will going run through is

  1. Analyze the problem
  2. Learn the method and structure
  3. Review the marking criteria
  4. Practice with the sample

Here the task 1 you get and you will solve this problem using TDD method.

Coffee App Study

Coffee App Feature Specs

BDD Specs

  • Story : User request to see coffee feed top list in 24 hours

Narrative 1

“As a online user I want the app to automatically load the coffee feed so I can see the newest coffee recipe”

Scenario of acceptance criteria

“Given the user connectivity and show the coffee list when the user open the app”

Let’s start to work on it

First we have to understand the Golden rule of TDD

  1. Write no production code except to pass a failing test
  2. Write only enough of a test to demonstrate a failure. (Not compiling is also a valid failure)
  3. Write only enough production code to past the test

In this case we will implement on the Infrastructure module especially for the remote login data.

Step 1 : Write the test code first

private val service = mockk<LoginService>
private lateinit var sut: LoginRetrofitClient

As you can see we net yet define the LoginService and LoginRetrofitClient class, yes that is the rule of TDD you can not write production code first. Now in our compiler that two classes will be red(error).

Step : 2

Now we already notice that we get the error, now it is time to implement the second rule of TDD.

interface LoginService{

}

class LoginRetrofitClient{

}

class LoginRetrofitClientTest {

private val service = mockk<LoginService>()
private lateinit var sut: LoginRetrofitClient
}

As we can see, now there is no error code anyome. It is time to implement the last rule:

interface LoginService{
fun login(email:String, password:String)
}


class LoginRetrofitClient : LoginService{
override fun login(email: String, password: String) {
TODO("Not yet implemented")
}
}
@Before
fun setUp(){
sut = LoginRetrofitClient(service)
}

@Test
fun testGetFailsOnConnectivityError() = runBlocking {
coVerify(exactly = 1) {
service.login(convertDto)
}
confirmVerified(service)
}

Now all the rule already implemented. The main reason why we should implemented.

--

--

Abi Farhan
Abi Farhan

Written by Abi Farhan

Sharing About Software Engineering, System Design, Test Drivent Development, and Data Structure and Algorithm.

No responses yet