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

Mock properties in a spied object, test run with Robolectric #263

Closed
ikhvostenkov opened this issue Feb 28, 2019 · 11 comments
Closed

Mock properties in a spied object, test run with Robolectric #263

ikhvostenkov opened this issue Feb 28, 2019 · 11 comments
Labels

Comments

@ikhvostenkov
Copy link

Expected Behavior

Properties of the spied objects should be mocked successfully.

Current Behavior

Properties of the spied objects are not mocked whatever property is public or private. But if I lazy initialize the field everything works perfectly.

Failure Information (for bugs)

I run a test with Robolectric and if I initialize property directly in the spied object, the property is not mocked, but as soon as I do lazy initialization mocking works.

Steps to Reproduce

Please provide detailed steps for reproducing the issue.

I have Fragment class like this:

class RoomsFragment : BaseFragment(), IRoomView {

    val presenter = RoomPresenter(BluetoothAdapter.getDefaultAdapter())
    private val adapter by lazy { RoomsAdapter(context) }
}

And I have tests to test it:

@RunWith(RobolectricTestRunner::class)
@Config(sdk = [Build.VERSION_CODES.O_MR1])
class RoomsFragmentTest {

    private val presenter = mockk<RoomPresenter>(relaxed = true)
    private val adapter = mockk<RoomsAdapter>(relaxed = true)
    private val roomsFragment = spyk<RoomsFragment>(recordPrivateCalls = true)
    private val room = Room("Room ID 1", "Room Name 1", RoomAvailability.FREE)

    @Before
    fun setUp() {
        every { roomsFragment getProperty "presenter" } returns presenter
        every { roomsFragment getProperty "adapter" } returns adapter
        startFragment(roomsFragment)
    }

    @Test
    fun `Fragment is created in the proper way`() {
        verify { presenter.startScan() }
    }
}

When I run like this, I have the real object instead of the mock for presenter property.
If I set presenter property private, I have io.mockk.MockKException: Missing calls inside every { ... } block.
And only if I lazy initialize presenter property with private val presenter by lazy { RoomPresenter(BluetoothAdapter.getDefaultAdapter()) } everything works good.

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • MockK version: 1.9.1
  • OS: macOS Mojave version 10.14.3
  • Kotlin version: 1.3.21
  • JDK version: 1.8.0_201
  • JUnit version: 4.12
  • Type of test: android unit test with Robolectric

Failure Logs

Please include any relevant log snippets or files here.

Stack trace

// -----------------------[ YOUR STACK STARTS HERE ] -----------------------
iio.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 com.gotomeeting.feature.npa.view.fragment.RoomsFragmentTest.setUp(RoomsFragmentTest.kt:42)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	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.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:256)
	at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
	at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
	at java.util.concurrent.FutureTask.run(FutureTask.java)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at java.lang.Thread.run(Thread.java:745)

// -----------------------[ YOUR STACK TRACE ENDS HERE ] -----------------------
@oleksiyp oleksiyp added the bug label Mar 9, 2019
@cristianoperez
Copy link

cristianoperez commented Mar 11, 2019

Same problem here, i cant mock spy properties

Steps do reproduce

class User(var status: Status){
    fun approve() {

        println("Status inside mocked class $status")

        if(status == Status.APPROVED){
            throw RuntimeException("User already approved")
        }

        this.status = Status.APPROVED
    }
}

enum class Status{
    PENDING, APPROVED
}


@Test(expected = RuntimeException::class)
fun `should approve user`(){
    val user = spyk<User>()
    every { user.status } returns Status.APPROVED

    println("Status inside test method ${user.status}")

    user.approve()
}
[main] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating spyk for User name=#1
[main] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for Status name=child of #1#2
[main] DEBUG io.mockk.impl.recording.states.AnsweringState - Answering APPROVED on User(#1).getStatus()
Status inside test method APPROVED
Status inside mocked class null
[main] DEBUG io.mockk.impl.recording.states.AnsweringState - Answering User(#1) on User(#1).approve()

@roccadev
Copy link

I get the same exception as OP's. In my case with a mock, not a spy, and in on-device instrumented test (not with Robolectric, the standard AndroidJunit4 runner). This happens only in instrumented tests.
Example:

mockk<AlbumCameraManager> {
                every { photoLiveData } returns fakeLiveData
            }
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:48)
at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:60)
at io.mockk.impl.eval.EveryBlockEvaluator.every(EveryBlockEvaluator.kt:25)
at io.mockk.MockKDsl.internalEvery(API.kt:92)
at io.mockk.MockKKt.every(MockK.kt:104)

androidTestImplementation "io.mockk:mockk-android:1.9"

Since I also use Mockito to work around other problems (like #237), could it be any interference? Because I noticed that this error didn't occur some times when launching isolated tests (i.e. running the test file or method directly) as opposed to launching the gradle task for all the instrumented tests, that makes it happen 100% of the times.

@oleksiyp
Copy link
Collaborator

Please check 1.9.2 as one race condition was fixed there.

@ikhvostenkov
Copy link
Author

@oleksiyp 1.9.2 did not fix the issue for me

@roccadev
Copy link

For me, io.mockk:mockk-android:1.9.2 somehow introduced a regression where the regular Byte Buddy is used... I can't tell anything about the discussed issue, had to go back to 1.9.

@oleksiyp
Copy link
Collaborator

Such thing may happen if Kotlin generate direct field access. Please check on byte code level if there is a method call. I think in Kotlin some optimizations were introduced that reduce getter generation at some cases

@xzamirx
Copy link

xzamirx commented Apr 16, 2019

On version 1.9.3 i got this problem too, sadly i cannot use the by lazy work around because the properties are being injected by dagger component

@stale
Copy link

stale bot commented Jul 23, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. If you are sure that this issue is important and should not be marked as stale just put an important tag.

@stale stale bot added the stale label Jul 23, 2019
@stale stale bot closed this as completed Jul 30, 2019
@oleksiyp
Copy link
Collaborator

oleksiyp commented Nov 2, 2019

Brief explanation. It is nearly impossible to mock private properties as they don't have getter methods attached. This is kind of Kotlin optimization and solution is major change. So keeping it closed as kind of duplicate for #104

@oleksiyp oleksiyp removed the stale label Nov 2, 2019
@annoyinglemon
Copy link

annoyinglemon commented Dec 23, 2019

The workaround I did is supplying my private property with 'VisibleForTesting' annotation.

@Nodrex
Copy link

Nodrex commented Oct 13, 2022

Any update on this ??

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

No branches or pull requests

7 participants