Hello all, I am trying to mock a private function ...
# android
b
Hello all, I am trying to mock a private function call in kotlin with mockk. Running into the following error, wondering if someone can help.
Copy code
Class is final. Put @MockKJUnit4Runner on your test or add MockK Java Agent instrumentation to make all classes 'open'
Code
Copy code
class ClassToTest {
  private fun privateMethod(text: String): String {
    return "Hello $text"
  }
}

class TestClass {

   @Before
   fun setup() {
      MockitoAnnotations.openMocks(this)
   }

   @Test
   fun testSplitNumbers() {
      val clazz = spyk<ClassToTest>()

      val method = clazz.javaClass.getDeclaredMethod("privateMethod", String::class.java)
      method.isAccessible = true
      val result = method.invoke(clazz, "Test") as? String
      Assert.assertEquals("Hello Test", result)
   }
}
m
Think @VisibleForTesting annotation may work on the line above privateMethod
b
I my case I cannot change ClassToTest. In addition I am fairly certain given my research that its possible to use reflection w/ spky/mockk to achieve the decided results w/o modifications to ClassToTest.
m
Yeah just a testing annotation...idk in the
testSplitNumbers
block maybe try
every { clazz.privateMethod("Test") } returns "Hello Test"
b
Thanks, that may work, however that would mock that function, not what I am after
v
Have you tried
mock-maker-inline
?
b
Using
testImplementation 'org.mockito:mockito-inline:5.2.0'
Guessing I have something wrong with my setup, not sure what though