arild
09/23/2019, 1:12 PMprivate val someMockedDependency: SomeClass = mockk()
vs @MockK private lateinit var someMockedDependency: SomeClass
?Big Chungus
10/01/2019, 8:32 AMexternal interface DElement : DNode {
}
Cody Engel
10/08/2019, 10:45 PMclearAllMocks
and unmockkAll
? I have the following test rule and when I used clearAllMocks
in the finished function I was seeing some tests failing because a mockkObject
wasn’t being cleared. With unmockkAll
though it resolved the issue.
class MockKTestRule(private val target: Any) : TestWatcher() {
override fun starting(description: Description?) {
super.starting(description)
MockKAnnotations.init(target)
}
override fun finished(description: Description?) {
unmockkAll() // clearAllMocks doesn't work for all use cases
super.finished(description)
}
}
But I don’t understand what the difference is? When would I want to use clearAllMocks
over unmockkAll
?rkeazor
10/17/2019, 1:49 AMYeray Cabello
10/23/2019, 6:54 AM() -> Unit
function as a parameter, but the matchers seem not to be able to get the mocking signature:
io.mockk.MockKException: Failed matching mocking signature for
left matchers: [any()]
What am I missing? I know that equality with lambdas can be a nightmare, but can't seem to find documentation on this.poohbar
10/30/2019, 1:28 PM@Before
fun setup() {
val instant = Instant.ofEpochMilli(1572400000000)
mockkStatic(Instant::class) {
every { Instant.now() } returns instant
}
}
Dennis Schröder
11/04/2019, 3:18 PMLeoColman
11/20/2019, 4:16 PMSamuel Michael
11/20/2019, 9:37 PMMark McCormick
11/27/2019, 3:13 PMinit
block in my ViewModel
. I would like to set some expected behavior of a mock I have inside the init
block like this every { repository.getSomething() } returns SomeEnum.A
. The problem is this expected answer is executed after the init
block. If I put the every { ... }
part to @Before
function it works fine, but I would like to set this expected answer only for one specific test. Any ideas?alostpacket
12/23/2019, 2:53 AMany<String>()
with just String
Kris Wong
12/23/2019, 8:14 PMkyleg
12/25/2019, 8:10 PMfoo: (File)->Long
I want to mock, and top-level (same file) caller: (foo: (File)->Long)->Int
that I do not want to mock, then that file needs @file:JvmName("FooKt") ; package <http://path.to|path.to>
up top, and then in the test:
with(::caller) {
mockkStatic("path.to.FooKt")
every { foo(any()) } returns 0L
this(::foo)
verify { foo(File("/path/to/thing") }
}
antoniomarin
01/16/2020, 1:38 PM// PRODUCTION
class classUnderTest(
private val preferences: Preferences
) {
fun changePreferenceToTrue() {
preferences.somePreference = true
}
}
// TEST
@Test
fun `Given preference false when changePreferenceToTrue then check is preference updated`() {
every { preferences.somePreference } returns false
classUnderTest.changePreferenceToTrue()
// I want to assert that this Preference is true
print(preferences.somePreference) // always returns as defined above, in this case false
}
voben
01/23/2020, 4:47 AMevery {} returns something
and
every {} answers {something}
voben
02/08/2020, 8:51 PMclass Repository(private val service: RetrofitService) {
suspend fun sendToken() {
val result = FirebaseInstanceId.getInstance().instanceId.await()
service.sendTokenToServer(result.token)
}
}
ivano
02/14/2020, 2:28 PMJohn Gainfort
02/25/2020, 11:10 PMjava.lang.ExceptionInInitializerError
at scte35decoder.Scte35DecoderTests.mockBase64Decoder(Scte35DecoderTests.kt:44)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:412)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalStateException: Error during attachment using: net.bytebuddy.agent.ByteBuddyAgent$AttachmentProvider$Compound@49aca0a6
at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:427)
at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:401)
at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:353)
at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:330)
at io.mockk.proxy.jvm.JvmMockKAgentFactory.initInstrumentation(JvmMockKAgentFactory.kt:134)
at io.mockk.proxy.jvm.JvmMockKAgentFactory.init(JvmMockKAgentFactory.kt:34)
at io.mockk.impl.JvmMockKGateway.<init>(JvmMockKGateway.kt:46)
at io.mockk.impl.JvmMockKGateway.<clinit>(JvmMockKGateway.kt:172)
... 48 more
Caused by: <http://java.io|java.io>.IOException: Cannot run program ""/Applications/IntelliJ IDEA <http://CE.app/Contents/jbr/Contents/Home/bin/java%22%22|CE.app/Contents/jbr/Contents/Home/bin/java"">: error=2, No such file or directory
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at net.bytebuddy.agent.ByteBuddyAgent.installExternal(ByteBuddyAgent.java:485)
at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:420)
... 55 more
Caused by: <http://java.io|java.io>.IOException: error=2, No such file or directory
at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:340)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:271)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
... 58 more
John Gainfort
02/25/2020, 11:10 PMinterface Foo { fun bar(val: String): ByteArray }
then in my commonTest I am trying to mock Foo
val mockedFoo = mockk<Foo> { every { bar("test") } returns ByteArray(1) }
my build.gradle.kts has
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
implementation("io.mockk:mockk:1.9.3")
implementation("io.mockk:mockk-common:1.9.3")
}
}
but when I go to run a test I get this error that I am having a hard time figuring out.Joan Colmenero
03/03/2020, 11:53 AMwithContext
from my viewModel and I'm planning to put it on the usecase
/ repository
something like this
launch{
updateView()
withContext(<http://Dispatchers.IO|Dispatchers.IO>){
doLogin(username,password)
}
updateView()
}
This is how I'm doing it now ^
Then if I want to remove the withContext(<http://Dispatchers.IO|Dispatchers.IO>)
I can do it like this
suspend fun doLogin(usernarme: String, password: String) = <http://Dispatchers.IO|Dispatchers.IO> { repo.doLogin(username,password)... }
So, is there any way to test it correctly?
I'm using mockK
so, I know with coEvery
is going to work, but is it safe to do not put Dispatchers.Uncofined
for testing purposes?
Also do you think it's a good idea to do not change context on viewModel and then just do this
launch {
updateView()
doLogin(username,password)
updateView()
}
Kris Wong
03/04/2020, 6:52 PMKulwinder Singh
03/10/2020, 1:30 PMMockKException: no answer found for: MyClass(#1).sendMessage(okhttp3.RequestBody$2@4ed4bd33)
,
actually RequestBody's properties are same just instance is different. that's why it did not matches parameters but if i add any()
instead of requestbody it works. is there anything else i can use instead of any()
here ?
every { myClass.sendMessage(MockRequest.createTestBody(value="text")) } answers { something }
....
class SomeObject(myClass:MyClass){
fun doSomething(text: String): Flowable<Result<Boolean>> {
val request = MockRequest.createTestBody(text)
myClass.sendMessage(request)
}
}
....
i have checked documentation of mockk but didn't found anything, that's why asked here:Erik
03/19/2020, 5:33 PMtestImplementation("com.github.erikhuizinga:mockk-junit4:1.0.0")
- For JUnit 5: testImplementation("com.github.erikhuizinga:mockk-junit5:2.0.0")
- For kotest a PR has been opened by @Sourabh Rawat, which I've reviewed.Ellen Spertus
03/25/2020, 12:15 AMprivate fun makeResolveInfo(appName: String, packageName: String, exported: Boolean = true) :
ResolveInfo {
val activityInfo = mockk<ActivityInfo>()
every { activityInfo.exported } returns exported
// remaining code omitted
The program crashes on the line with every
:
io.mockk.MockKException: Missing calls inside every { ... } block.
at io.mockk.impl.recording.states.StubbingState.checkMissingCalls(StubbingState.kt:14)
at io.mockk.impl.recording.states.StubbingState.recordingDone(StubbingState.kt:8)
at io.mockk.impl.recording.CommonCallRecorder.done(CommonCallRecorder.kt:47)
at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:60)
at io.mockk.impl.eval.EveryBlockEvaluator.every(EveryBlockEvaluator.kt:30)
at io.mockk.MockKDsl.internalEvery(API.kt:92)
at io.mockk.MockKKt.every(MockK.kt:104)
at mozilla.voice.assistant.intents.MetadataTest$Companion.makeResolveInfo(MetadataTest.kt:61)
Any idea what I’m doing wrong? The file is in a test
directory rather than androidTest
. I don’t know if that could be a problem.Dave Leeds
03/27/2020, 8:29 PMcoEvery { httpClient.hint(MyPayload::class).get<MyPayload>(any<String>()) }.returns(examplePayload)
But this fails with a class cast exception:
MyPayload cannot be cast to io.ktor.client.call.HttpClientCall
I suspect the reason for this is that the entire call stack between the test and HttpStatement.executeUnsafe()
is made up of inline
functions. I tried to mock httpClient.execute()
since that’s ultimately what gets invoked, but that’s marked as @InternalAPI
. Any ideas?Kris Wong
04/22/2020, 6:37 PMmockkObject(AppLockedState)
every { AppLockedState.isLocked() } answers { locked }
it seems to be executing the isLocked
method rather than using the answer. it's complaining that Boolean can't be cast to one of the types being used in the method implementationKris Wong
04/23/2020, 2:11 PMKris Wong
04/23/2020, 2:22 PMmockkObject(IntentQueueFactory)
every { IntentQueueFactory.getInstance(context) } returns queue
causes
io.mockk.MockKException: Missing calls inside every { ... } block.
at io.mockk.impl.recording.states.StubbingState.checkMissingCalls(StubbingState.kt:14)
at io.mockk.impl.recording.states.StubbingState.recordingDone(StubbingState.kt:8)
at io.mockk.impl.recording.CommonCallRecorder.done(CommonCallRecorder.kt:47)
at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:60)
at io.mockk.impl.eval.EveryBlockEvaluator.every(EveryBlockEvaluator.kt:30)
at io.mockk.MockKDsl.internalEvery(API.kt:92)
at io.mockk.MockKKt.every(MockK.kt:98)
Kris Wong
04/23/2020, 2:55 PMAlex Kuznetsov
05/01/2020, 5:59 PMmockk
statement:
I'd like to spread a long statement like the following over several lines:
every { <http://myThing.do|myThing.do>() } returns 1 andThenThrows Exception("No way!") andThen 3 andThen 4
the line gets too wide, is there a way to continue it:
every { <http://myThing.do|myThing.do>() } returns 1
andThenThrows Exception("No way!")
andThen 3
andThen 4
TIA!Alex Kuznetsov
05/01/2020, 5:59 PMmockk
statement:
I'd like to spread a long statement like the following over several lines:
every { <http://myThing.do|myThing.do>() } returns 1 andThenThrows Exception("No way!") andThen 3 andThen 4
the line gets too wide, is there a way to continue it:
every { <http://myThing.do|myThing.do>() } returns 1
andThenThrows Exception("No way!")
andThen 3
andThen 4
TIA!jdiaz
05/02/2020, 7:32 PMreturns(1).andThenThrows(...).andThen(3)
and then you can format it as you wantAlex Kuznetsov
05/18/2020, 9:35 PM