Skip to content

Use randomK in your tests to create real objects with fake data automatically.

License

Notifications You must be signed in to change notification settings

sylhare/RandomK

Repository files navigation

RandomK

Create random instance from a class. It uses kotlin-reflect to create by reflection the instance. (Using KClass and KType)

Reflection is a set of language and library features that allows for introspecting the structure of your own program at runtime.

Based on Marcin Moskala from Kt Academy 's article:

How to use

Add the dependency

Create a GitHub Personal Access Token

To use the packages hosted on the GPR (GitHub Package Registry) you need your username/token. Add the GPR as a repository inside your build.gradle.kts:

maven {
    url = uri("https://maven.pkg.github.com/sylhare/RandomK")
    credentials {
        username = project.findProperty("gpr.user") as String? ?: System.getenv("USERNAME")
        password = project.findProperty("gpr.key") as String? ?: System.getenv("TOKEN")
    }
}

You can set those variables using:

export USERNAME="my-github-username"
export TOKEN="my-secret-personal-access-token-for-github"

Then add the randomK dependency:

dependencies {
    implementation("com.github.sylhare:randomk:$randomKVersion")
}

With the latest version available, check out the package section 😉

Find the full example here.

In your code

Since we're using typeOf<T>() fom kotlin-reflect to detect the retention type (introduced in kotlin v1.3), the library is under the @ExperimentalStdlibApi.

You can create a random instance with randomK like:

private val example: Example = randomK()
private val otherExample = randomK<OtherExample>()

It will create a random instance.