Endre Deak
06/03/2024, 2:53 PMinterface X<T: Comparable<T>> {
fun get(): T
}
@Test
fun `test x`() {
val x = mockk<X<Int>>()
every { x.get() } returns 1 # fails
every { x.get().hint(Int::class) } returns 1 # fails
val result = x.get()
result shouldBe 1
verify(exactly = 1) {
x.get()
}
}
# workaround:
interface TypedX : X<Int>
@Test
fun `test x`() {
val x = mockk<TypedX>()
every { x.get() } returns 1 # passes
val result = x.get()
result shouldBe 1
verify(exactly = 1) {
x.get()
}
}
The error I get:
Class cast exception happened.
Probably type information was erased.
In this case use `hint` before call to specify exact return type of a method.
io.mockk.MockKException: Class cast exception happened.
Probably type information was erased.
In this case use `hint` before call to specify exact return type of a method.
Caused by: java.lang.ClassCastException: class io.mockk.renamed.java.lang.Number$Subclass3 cannot be cast to class java.lang.Comparable (io.mockk.renamed.java.lang.Number$Subclass3 is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
...
David Kubecka
06/04/2024, 1:20 PMfun <T> execute(operation: Operation, contract: ContractDTO, block: () -> T): T
every { execute(any(), any(), captureLambda()) } answers {
lambda<() -> ???>().invoke()
}
How to specify the lambda
type so that it can be used for any actual type T
?David Kubecka
06/06/2024, 8:33 AMfun <T> assertEqualsRecursive(actual: T, expected: T, vararg ignoringFields: String) {
assertThat(actual)
.usingRecursiveComparison().withStrictTypeChecking().ignoringFields(*ignoringFields)
.isEqualTo(expected)
}
In my actual test case I'm capturing a list argument into a slot:
val messageValuesSlot = slot<List<SomeType>>()
val actualMessages = messageValuesSlot.captured
and then comparing it with an expected list:
assertEqualsRecursive(actualMessages, listOf(...))
The problem is that thanks to the withStrictTypeChecking
option the comparison fails with
actual and expected are considered different since the comparison enforces strict type check and expected type java.util.Arrays$ArrayList is not a subtype of actual type java.util.ArrayList
So if I understand it correctly
• There are for some reason two ArrayList
in java.util
• The listOf
constructor uses different ArrayList
than the mockk when filling the messageValuesSlot
Why is that? Why mockk doesn't use listOf
? Is there anything I can do about that other than reverse-engineer mockk and use the same ArrayList
?Larry Garfield
07/03/2024, 4:38 PMKev
07/13/2024, 9:16 AMInconsistent number of parameters in the descriptor and Java reflection object: 3 != 2
. Common code between the tests are:
data object MyError1
data object MyError2
@JvmInline
value class TestId(val id: String)
Failing code:
class Foo {
context(Raise<MyError2>)
suspend fun foo(): TestId {
return TestId("hello")
}
}
class Service(private val foo: Foo) {
context(Raise<MyError1>)
suspend fun test(): TestId {
return withError({ MyError1 }) {
foo.foo()
}
}
}
test("test 1") {
val foo = mockk<Foo>()
val service = Service(foo)
coEvery {
with(any<Raise<Any>>()) {
foo.foo()
}
}.coAnswers { TestId("hello") }
either {
service.test()
}.shouldBeRight()
}
Passing code (where instead of having a TestId
return type, I have a String
return type.
class Foo {
context(Raise<MyError2>)
suspend fun foo(): String {
return "hello"
}
}
class Service(private val foo: Foo) {
context(Raise<MyError1>)
suspend fun test(): String {
return withError({ MyError1 }) {
foo.foo()
}
}
}
test("test 1") {
val foo = mockk<Foo>()
val service = Service(foo)
coEvery {
with(any<Raise<Any>>()) {
foo.foo()
}
}.coAnswers { "hello" }
either {
service.test()
}.shouldBeRight()
}
Daniele Andreoli
08/01/2024, 9:13 AM@MockK
lateinit var mockAnalyticsReporters: List<AnalyticsReporter?>
when using this I recieve this strange error:
class kotlin.Unit cannot be cast to class java.lang.Boolean (kotlin.Unit is in unnamed module of loader 'app'; java.lang.Boolean is in module java.base of loader 'bootstrap')
java.lang.ClassCastException: class kotlin.Unit cannot be cast to class java.lang.Boolean (kotlin.Unit is in unnamed module of loader 'app'; java.lang.Boolean is in module java.base of loader 'bootstrap')
at io.mockk.renamed.java.util.Iterator$Subclass5.hasNext(Unknown Source)
I actually can’t understand what this means. I’m not a very well tester so i need some help. Thanks.Vaibhav Jaiswal
09/13/2024, 7:24 AMval user = User(
displayName = "",
contactNumber = "",
location = null,
email = "",
profileImageUrl = "",
connectionCount = 0,
followersCount = 0,
id = "",
summary = "",
tagline = "",
slug = "",
totalExperienceInMonths = 0,
createdAt = DateHelpers.now,
isFollowed = false,
)
val resultUser = user.copy(token = Arb.string().
coEvery {
apiService.createUser(user, "", "")
} returns resultUser
//call function to test
userRepo.createUser(user, "", "")
Which returns fine, when i debug using breakpoints
But the function which I am testing, does this internally
preferences.user = json.encodeToString(user)
Which crashes the test, even though the type User is Serializable
Stack trace in thread 🧵Chuong
10/06/2024, 11:22 PMEnum
class with kotlinx-serialization
.
@Serializable
enum class Certificate {
@SerialName("Certificate_A") A
}
For the purposes of testing, I want to add another Enum
entry.
@SerialName("Certificate_B") B
How do I do that with mockk
?Mattia Tommasone
10/08/2024, 11:42 AMMattia Tommasone
10/09/2024, 12:13 PMVaibhav Jaiswal
10/12/2024, 4:26 AMMarek Kubiczek
10/16/2024, 1:52 PMmockkStatic
safe to use with parallel test execution? I mean the Gradle option maxParallelForks
. My understanding is it just spawns multiple jvm processes with their own class loaders. As such static mocks from one process shouldn't leak to the other, correct?. As I understand tests are still run sequentially within each process.
In reality though we see test failures that look like they leak happens. We use Junit4 and it's Android project.David Corrado
10/31/2024, 4:00 PMphldavies
11/26/2024, 10:58 AMShubo
12/16/2024, 5:13 AMVinicius Matheus
12/16/2024, 1:37 PMvalue class
return with the 1.13.13 version?André Martins
12/20/2024, 3:04 PMio.mockk.MockKException: No other calls allowed in stdObjectAnswer than equals/hashCode/toString
but no clue why this is happening 😓
Has anyone got this exception before?
Thanks in advance ✌️hho
01/21/2025, 10:17 AM@InjectMockKs
etc. are not, in fact, unused?Noah
01/30/2025, 4:09 PMrepository
every { repository.save(any()) } returns fleetEntity
Returns the following after switching JDK from Eclipse Temurin to docker.io/ibm-semeru-runtimes:open-17.0.13_11-jdk
FleetServiceTest > should return created fleet given request() FAILED
io.mockk.MockKException at FleetServiceTest.kt:44
Caused by: java.lang.ClassCastException at FleetServiceTest.kt:44
repository interface:
package org.springframework.data.repository;
import java.util.Optional;
@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S entity);
<S extends T> Iterable<S> saveAll(Iterable<S> entities);
Optional<T> findById(ID id);
boolean existsById(ID id);
Iterable<T> findAll();
Iterable<T> findAllById(Iterable<ID> ids);
long count();
void deleteById(ID id);
void delete(T entity);
void deleteAllById(Iterable<? extends ID> ids);
void deleteAll(Iterable<? extends T> entities);
void deleteAll();
}
Any ideas as to why this CastException occurs all of a sudden after changing the JDK? This is important because the new JDK image has a significantly smaller memory footprint.Michael de Kaste
02/25/2025, 1:31 PMclass Organisation(
var name: String,
)
val organisation = mockk<Organisation>()
val property: KMutableProperty0<String> = mockk()
every { organisation::name } returns property
this does not work because the every { ... } call does not contain a mocked callJacob
03/03/2025, 1:20 AMKlitos Kyriacou
04/15/2025, 3:54 PMevery {
constructedWith<MockCls>(OfTypeMatcher<String>(String::class)).add(2) // Mocks the constructor which takes a String
} returns 3
Why does OfTypeMatcher
need to have the type String
mentioned twice? If it was defined differently, we would be able to have just OfTypeMatcher<String>()
(if we used reified generics), or just OfTypeMatcher(String::class)
. Perhaps I've misunderstood its usage and the two String
type references don't have to be the same?Emre
04/25/2025, 2:53 AMMikolaj
06/02/2025, 10:37 AMprivate val i18n: I18n = mockk<I18n> {
every<String> { any() } returns ""
}
Mattia Tommasone
06/22/2025, 9:29 PMEdgar
07/01/2025, 11:32 AMCannot access class 'MockKMatcherScope'. Check your module classpath for missing or conflicting dependencies.
Does anyone have some clue about this? Thank you so much in advance!Arnab
07/09/2025, 8:36 AMclass Bar {
fun foo(arg1: String, arg2: String? = null) = "Hello World"
}
How can I mock this without providing matchers for all arguments in the function? Essentially I want to do something like this:
every { barMock.foo } returns "Something Else"
Matteo Mirk
07/11/2025, 9:22 AMclearAllMocks()
, is it thread-safe? Will it somehow clear only this class/thread mocks or will it bulldoze everything within the same process? Can it affect the behaviour of another test running in parallel?v79
07/13/2025, 6:43 PMjava.io.File
object and it's not going well. I've just seen the documentation that says that this class is restricted by default, and cannot be mocked. I definitely used to be able to... seven years ago! What's the best practice for handling these files in mockk now?v79
07/31/2025, 9:58 PMcoVerify
insists it was not called.
no answer provided for DynamoDBService(#8).upsertContentNode(eq(domain.com/sources/posts/my-post.md), eq(domain.com), eq(Posts), any(), eq({}), any()))
And yet...
declareMock<DynamoDBService> {
every { mockDynamoDBService.logger = any() } just runs
every { mockDynamoDBService.logger } returns mockLogger
coEvery {
mockDynamoDBService.upsertContentNode(
"domain.com/sources/posts/my-post.md", "domain.com",
SOURCE_TYPE.Posts,
any<ContentNode.PostNode>()
)
}
}