Nicklas Jensen
11/23/2021, 2:41 PM@Mock
and assigning it to the value of a call to the <T> mock(KClass<T>)
function:
class GitHubServiceTests {
@Mock
val api = mock(GitHubAPI::class)
}
Please see the README for instructions on how to get started using Mockative today. We would love to hear your feedback on the framework.Big Chungus
11/23/2021, 2:49 PMinline fun <reified T> mock() = mock(T::class)
class GitHubServiceTests {
@Mock
val api: GitHubAPI = mock()
@Mock
val api2 = mock<GitHubAPI>()
}
Nicklas Jensen
11/23/2021, 2:50 PMephemient
11/23/2021, 2:56 PMtypeOf<T>()
? as T::class
does not carry any information about type parametersNicklas Jensen
11/23/2021, 3:00 PMinline
function with a reified
type parameter appears compatible at first sight, the bytecode turns out different in a way that leaves it incompatible. Thank you for the suggestions though 🙂!ephemient
11/23/2021, 3:05 PMmock*()
name, so that you can write
class Test {
@Mock val x: Foo<X> = mockFooX()
@Mock val y: Foo<Y> = mockFooY()
}
?Nicklas Jensen
11/23/2021, 3:05 PMtypeOf<T>()
returns a KType
with no type information (at compile time), and as such, will not work with Mockative. We’ll have a look into whether we can support generic types.ephemient
11/23/2021, 3:06 PMmock*()
function for every @Mock
encountered in the source code?ephemient
11/23/2021, 3:07 PMNicklas Jensen
11/23/2021, 3:08 PMephemient
11/23/2021, 3:08 PMNicklas Jensen
11/23/2021, 3:10 PM@Mock
, which calls <T> mock(KClass<T>)
. This is where the quirk is useful and where an inline
function prevents things from workingephemient
11/23/2021, 3:12 PMNicklas Jensen
11/23/2021, 3:12 PMmock*()
question, then yes, we absolutely could generate a function for each mock, and in fact we’re already generating a class for each mock accepting 0 arguments, with the suffix Mock
. These can be used in place of the result of a call to <T> mock(KClass<T>)
, if you so desireNicklas Jensen
11/23/2021, 3:16 PMfun <T> mock(KClass<T>)
with a call to inline fun <reified T> mock()
, because overload resolution with generated code appears to work differently with inline functions. Mockative uses a quirk of the Kotlin compiler where it will select the generated mock(KClass<GitHubAPI>)
function over the generic mock(KClass<T>)
function, as long as they’re in the same package.
Please check out the repository and see the effect for yourself, and feel free to submit a Pull Request if you come up with a more concise way that remains compatible 🙂ephemient
11/23/2021, 3:18 PMephemient
11/23/2021, 3:20 PMNicklas Jensen
11/23/2021, 3:20 PMNicklas Jensen
11/23/2021, 3:22 PMephemient
11/23/2021, 3:22 PM@ThreadLocal
should be safe if you're not on the new memory managerephemient
11/23/2021, 3:23 PMmock()
method with a big when
statement inside 😆Big Chungus
11/23/2021, 3:39 PM