Mendess
12/10/2021, 10:58 AMclass Foo {
val prop get() = 1
}
val aFoo = Foo()
val myService = MyService(aFoo)
myService.method() // should access Foo::prop
verify {
aFoo.prop // doesn't work
}
Kaushalya
01/25/2022, 3:39 PMVivek Modi
01/26/2022, 2:00 PMVivek Modi
01/26/2022, 10:38 PMinternal fun handleDataResponse() {
dataLiveData.postValue(true)
currentDeviceTypeLiveData.postValue(true)
}
test
@Test
fun `handleDataResponse - Handle connection success `() {
// STUBBING
// EXECUTION
viewModel.handleDataResponse()
// VERIFICATION
assertEquals(true, viewModel.dataLiveData.value)
assertEquals(true, viewModel.currentDeviceTypeLiveData.value)
}
tim
02/09/2022, 8:27 PMvalue class
, is this a known issue?Anton Afanasev
02/15/2022, 4:48 PMclass Example (val dependency : Dependency, val anotherDependency: AnotherDependency ){
fun doWork() {
dependency.doSomething()
anotherDependency.doSomethingElse()
}
}
class Dependency() {
fun doSomething() {
println("do something")
}
}
class AnotherDependency() {
fun doSomethingElse() {
println("do something")
}
}
Test Class:
class ExampleTest {
private val mockDependency = mockk<Dependency>(relaxed = true)
private val mockAnotherDependency = mockk<AnotherDependency>(relaxed = true)
val subject = Example(mockDependency, mockAnotherDependency)
@Test
fun `when doWork called`() {
subject.doWork()
verifyOrder {
mockDependency.doSomething()
}
}
}
My tests are passing even though I never verified that mockAnotherDependency.doSomethingElse()
invocation. I wonder if there any way to tell mockk to enforce that if any mock object participating in test-case was not verified the test case fails.
Without that check I can seamlessly remove:
anotherDependency.doSomethingElse()
from my actual Example.doWork() and tests will still pass.Michael Vandendriessche
02/24/2022, 2:48 PMClassWithManyStaticMethods.getSomething().method(lateInitialisedField)
I finally figured out how to mock the static class but stumble upon following error
lateinit property lateInitialisedField has not been initialized
.
So the lateInitialisedField
is a lateinit in the class I want to test. When I call the function I want to test, the lateInitialisedField
is not initialised.
How do I initialise it in the test or prevent the error? The value does not matter for my test, I just want to verify if method
has been called.
I tried using @InjectMocks
when I create the class under test and created a mockk lateInitialisedField
in my test but either I'm doing something wrong or this is not the solution.
If anyone could point me in the right direction that would be greatly appreciated!Szymon Jeziorski
02/26/2022, 1:01 PMverify
- verifying method call with the argument being an object equal to another object comparing field by field but ignoring one or more fields.
So far the only reasonable solution I came up with was creating a matcher
using AssertJ's usingRecursiveComparison()
and wrapping it to `runCatching`:
inline fun <reified T : Any> MockKVerificationScope.matcherFor(expected: T, vararg ignoredFields: String) = match<T> {
runCatching {
assertThat(it).usingRecursiveComparison().ignoringFields(*ignoredFields).isEqualTo(expected)
}.isSuccess
}
example usage:
verify {
userRepository.save(matcherFor(expectedUser, "id"))
}
I found the above to be elegant enough from the calling side but was wondering if there would be any more straightforward way to achieve the same with less overhead at the same time.
Thanks in advance for any suggestions!Michael Vandendriessche
03/02/2022, 3:26 PMSomeClass
. Do I have to return SomeClass()
or is there something else available like return any or return whatever?Klitos Kyriacou
03/03/2022, 5:51 PMResultSet
, and therefore its getLong()
method returns a JVM platform type (i.e. it could be Long
or Long?
):
val id: Long? = <...>
every { resultSet.getLong("id") } returns id
Unfortunately, this results in the error message "Type mismatch: inferred type is Long? but Long was expected." Is this a bug, a known limitation, or something I'm doing wrong? I can work around it like this:
every { resultSet.getLong("id") as Long? } returns id
but then IntelliJ IDEA warns me that as Long?
is unnecessary.phldavies
03/09/2022, 8:23 PMjmfayard
03/10/2022, 12:37 PMsealed class Either
which either a Left
or a Right
But actually no, because in my unit tests, mockk creates a subclass of Either
which is neither Left nor Right and break the contract of my type
Is there a way to forbit mockkk to create a subclass of a sealed class?Matthew Laser
03/10/2022, 4:48 PMinline
functions aren’t mockable (and not spyable from what I can tell?)
does anyone have strategies for verifying that calls to a `MutableStateFlow`’s inline fun <T> MutableStateFlow<T>.update(function: (T) -> T)
is invoked with the correct argument (or invoked at all)?Pitel
03/22/2022, 10:43 AMDavis Mohar
03/25/2022, 2:56 PMtimed()
function that I'm trying to mock:
interface Metrics {
suspend fun <T> timed(name: String, f: suspend () -> T): T
}
So you would think you could mock that with:
val mockMetrics: Metrics = mockk()
val funSlot = slot<suspend () -> Either<Nothing, Transfer>>()
coEvery { mockMetrics.timed(any(), capture(funSlot)) } coAnswers { funSlot.captured() }
mockMetrics.timed("metricName") { foo() }
That is only sometimes correct, which is the worst kind of correct. Depending on how I run the tests (kotest tests running on gradle), the test containing this mock will pass sometimes. When it fails, we get a
io.mockk.MockKException: no answer found for: Metrics(#3).timed(mmp.process.transfer.latency, continuation {}, continuation {})
which implies that timed
takes three arguments. I believe that's expected behavior, based on how suspend functions compile behind the scenes. But that also implies that our installed answer on our mocked timed
call complied differently -- but only sometimes. Has anyone dealt with behavior like this before? My current workaround is just writing a custom little MockMetrics class instead of using mockk for it.André Martins
03/31/2022, 4:24 PMAndré Martins
03/31/2022, 4:27 PMunmockkStatic
or clearStaticMockk
after done using the static mock?aherbel
04/07/2022, 6:45 PMon
on Mockito but in MockK? I need to change the response type of an every
call but I found no operator to do this as with the on
operator in Mockitomcpiroman
04/09/2022, 6:39 PMfun prepareStatement(sql: String): PreparedStatement
fun prepareStatement(sql: String, resultSetType: Int): PreparedStatement
fun prepareStatement(sql: String, resultSetType: Int, resultSetConcurrency: Int): PreparedStatement
fun prepareStatement(sql: String, resultSetType: Int, resultSetConcurrency: Int, resultSetHoldability: Int): PreparedStatement
What if I want to mock all of them in the same way, whereas I only care about the `sql`parameter?
Currently I repeat every {
block for each overload. Is there more preferred way, e.g. matching functions by name?Jérémy CROS
04/13/2022, 3:42 PMclass DummyUseCase {
operator fun invoke(): String = TODO()
}
@Test
fun test() {
val dummyUseCase1: DummyUseCase = mockk()
every { dummyUseCase1.invoke() } returns ""
val dummyUseCase2: DummyUseCase = mockk {
every { this.invoke() } returns ""
}
}
In the second case, I have a compilation error: “Not enough information to infer type variable T”
(I’m fine with the first declaration but we’ve been trying this operator invoke
thing for our use cases that was showcased in one of the recent MAD Skills video and we use sometimes the second mock declaration)
Thanks! 🙂Chico
04/13/2022, 7:15 PMDictKey.get call, but I'm having this problem Type mismatch: inferred type is DictKey but MockKMatcherScope.DynamicCall was expected
class A {
fun callExternalApi(key: String) {
return DictKey.get(key)
}
}
But DictKey.get return an instance Of DictKey(….) I would like to stub it
What I’m doing..
val key = "my-key"
val mockDt = mockk<DictKey>()
every { mockDt.get(key) } returns what I have to put here?
val retruanCallExternalApi = A().callExternalApi(key)
Michael de Kaste
04/14/2022, 2:57 PMChico
04/14/2022, 4:24 PMfun <T> dummy(arg: Int, argTwo: T) {
//do something with argTwo
}
I tried to mock with
mockkStatic(::dummy)
but it said
not enough information to infer T, so does anyone knows how can I solve it?Peter Farlow
04/19/2022, 6:46 PMAnalytics
object, but unfortunately mockk<Analytics>()
cannot create a mock because of a static android Handler in that class:
public class Analytics { // this is 3rd party code I can't change
static final Handler HANDLER =
new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
throw new AssertionError("Unknown handler message received: " + msg.what);
}
};
// rest of class here
}
I tried using both mockk<Analytics>()
and adding mockkConstructor(Handler::class)
but that didn’t work. Any suggestions?André Martins
04/20/2022, 4:41 PMCoroutineCollection
with the following code
data class User(val id: Int, val name: String)
class Service(private val myDatabase: CoroutineDatabase) {
private val userCollection: CoroutineCollection<User> = myDatabase.getCollection("users")
suspend fun getById(id: Int): User? = userCollection.findOneById(id)
// ...
suspend fun insertUser(user: User): InsertOneResult = userCollection.insertOne(user)
}
@Test
fun myTest(): Unit = runBlocking {
// Arrange
val database = mockk<CoroutineDatabase>()
val userCol = mockk<CoroutineCollection<User>>()
every {
database.getCollection<User>("users")
} returns userCol
val service = Service(database)
val expectedUser = User(30, "Joe")
coEvery {
userCol.findOneById(30)
} returns expectedUser
// Act
val actualUser = service.getById(30)
// Assert
assertEquals(expectedUser, actualUser)
}
The error is
class org.litote.kmongo.coroutine.CoroutineCollection cannot be cast to class com.mongodb.reactivestreams.client.MongoCollection (org.litote.kmongo.coroutine.CoroutineCollection and com.mongodb.reactivestreams.client.MongoCollection are in unnamed module of loader 'app')
I suspect this is due to functions like CoroutineDatabase::getCollection<T>(String)
being inlinepepe
04/21/2022, 8:34 AMAndré Martins
04/21/2022, 12:12 PMclass MyService { … }
and an extension property like
val MyService.myProp: String
get() = "value"
when doing
mockk<MyService> {
every { myProp } returns "otherValue"
}
it throws a MockkException
msg: Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock
André Martins
04/26/2022, 10:52 AMcoEvery
to mock a specific function although somehow the coEvery
call is hanging when I run the test. What can cause this hanging?Klitos Kyriacou
04/29/2022, 12:16 PMMichael de Kaste
05/13/2022, 9:10 AMevery { someClass.duration } returns 30.minutes
I can't run thisMichael de Kaste
05/13/2022, 9:10 AMevery { someClass.duration } returns 30.minutes
I can't run thisephemient
05/13/2022, 11:08 AMMichael de Kaste
05/13/2022, 11:31 AMephemient
05/13/2022, 1:29 PMevery { someClass.duration as Any? }.returns(30.minutes as Any?)
work? (just a thought, there's a good chance that doesn't help) otherwise you'll just have to avoid mocking by using the real object or a writing a fake