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 The Android Architect cohort #2

6 weeks cohort course on Architecture and Mobile Devops

✅ Mentor + peer homework review

Learn from Kotlin GDE, Jarosław Michalik: Draw on the expertise of a seasoned Android professional.


high-level design guide for Android Architects


Wow finally something straightforward” ~ Marcin, Senior Android Engineer

  • high-level design overview
  • explanatory video
  • you were probably looking for it for a long time

Read more:

  • #kotlinDevChallenge 2023 summary

    #kotlinDevChallenge 2023 summary

    The KotlinDevChallenge was not just a competition, but a journey of learning, growth, and community engagement. Every participant in this challenge is a winner…

  • #kotlinDevChallenge – 24

    #kotlinDevChallenge – 24

    What do you love most about Kotlin? Productivity increase? Idioms? Or that it isn’t Java? Maybe something else! Share it. It can be short.…

  • #kotlinDevChallenge – 23

    #kotlinDevChallenge – 23

    Challenge checking your generics knowledge 🙂 No long description is necessary. You can select more than one answer. Good luck!