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?
CodePudding user response:
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.