Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to return generic type for a fixture to return a fixture with configuration builder properties ? #81

Closed
istvandesign opened this issue Feb 22, 2021 · 1 comment

Comments

@istvandesign
Copy link

istvandesign commented Feb 22, 2021

Hello, I tried to return a kotlinFixture in a function with ConfigurationBuilder, but I discovered that I have no idea what type it will return.

Is there any way to return the correct type for

private fun myReusableFixture(): Sometype = kotlinFixture { property(X::y) { y } }

It will complain when used as fun fixture() = myReusableFixture() and then fixture() in the every mockk.

I want to return the same fake values in multiple tests, now it generates a new fake value that I have no reference to.

@mattmook
Copy link
Member

mattmook commented Feb 22, 2021

kotlinFixture { ... } returns a com.appmattus.kotlinfixture.Fixture. The Fixture class and its configuration is immutable and stateless by nature.

As a function you'd need to call it as myReusableFixture()(). However, there's nothing stopping you storing your shared configuration in a top-level val:

private val myReusableFixture = kotlinFixture { property(X::y) { y } }

Regardless of whether this is a fun or val you will always get different values back when calling myReusableFixture<Type>() as it is random by nature.

To mitigate this the easiest suggestion for when you need to refer to one of the values is to create the needed instance outside of your mock, so something like this:

@Test
fun myTest {
    // If a lot of your tests are generating the same fixture this could be generated as a class member instead
    val outcome = myReusableFixture<Outcome>()

    val car = mockk<Car>()
    every { car.drive(Direction.NORTH) } returns outcome

    ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants