简体   繁体   中英

MockK Mocking a Surface object for Android

I'm trying to test some code, and I need a valid Surface object for Android in order to properly test it, since a lot of the code checks if there is a valid surface (ie surface.isValid() where surface is of the Surface class: https://developer.android.com/reference/android/view/Surface )

With MockK, is there a way I can essentially perform this Mock? I have tried the following:

private lateinit var mymonitor : Monitor
@MockK private lateinit var mockContext : Context
@MockK private lateinit var mockSurface : Surface

@Before
fun setup() {
   init(this, relaxed = true)
   mockkConstructor(Monitor::class)
   mockkConstructor(Surface::class)
   every { anyConstructed<Monitor>().getApplicationContext() } returns mockContext
   every { anyConstructed<Surface>().isValid() } returns true

   mymonitor = spyk(Monitor())
   mymonitor.init(mockContext, mockSurface)

In the Monitor.java file

protected void init(Context mockContext, Surface mockSurface) {
   if (mockSurface.isValid()) {
      Log.d(TAG, "Surface is valid...");
      // proceeds with init
   } else {
      Log.d(TAG, "Surface NOT valid...");
   }
}

When I do this, I get the Log that Surface NOT valid , so basically the Surface object is not valid I suppose. Am I doing something wrong?

Try remove the anyConstructed:

private lateinit var myMonitor : Monitor
private val mockContext : Context = mockk(relaxed = true)
private val mockSurface : Surface = mockk(relaxed = true)

@Before
fun setup() {
    every { mockSurface.isValid() } returns true

    myMonitor = spyk(Monitor())
    myMonitor.init(mockContext, mockSurface)
}

PD: In case of needing to use a real context, it would be necessary to apply Robolectric or an android test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM