How to mock data class?

|

Short answer: you don’t.

Instead: create additional function.

Let’s suppose, you have User data class.

data class User(val id: Int, val name: String, val email: String)

The easiest way to “mock” it would be to use default values. But does default values always makes sense? If it’s json model, it may not be the best solution.

Create additional function createUser that will accept the same values as your data class. Now you can use “defaults” by calling that function.

fun createUser(
    id: Int = 1,
    name: String = "",
    email: String = ""
): User {
    return User(id, name, email)
}

But what if I need many of those users?

Glad you asked.

Create another function. Now you can generate as many unique Users as you want.

fun generateUsers(howMany: Int) = List(howMany){index->
    User(
        id = index,
        name = "Name #$index",
        email = "user_$index@domain.com"
    )
}

We usually refer all test doubles as “mocks”.

Keep it in mind while testing.

Join AndroidPro newsletter & get roadmap for Android devs

👉 Architecture
👉 CI/CD
👉 Testing
👉 Compose
👉 projects to learn from
… in a single document


Read more:

  • #kotlinDevChallenge – 10

    #kotlinDevChallenge – 10

    Implement a function that sums the first 5 even numbers from each of three given integer Flows and returns their total sum. Properly handle…

  • #kotlinDevChallenge – 9

    #kotlinDevChallenge – 9

    Write a function that takes a list of lists of integers and returns a single list containing all unique elements. Ensure that the resulting…

  • #kotlinDevChallenge – 8

    #kotlinDevChallenge – 8

    data class A is given. We create an instance of this class and then call the .copy() function. What will be printed out? Mark…