androidkotlinunit-testingmethodsprotected

how to access protected method inside unit test on kotlin


is there a way to get inside protected value and access it on kotlin unit test, below are my doPost protected method, i tried with reflection but its not working, following this sample https://stackoverflow.com/a/41695398/6377156

myimage

@Mock
internal lateinit var jobServlet:myHttpServlet

private val mockContext = mockk<Context>(relaxed = true)
private val mockHttpRequest = mockk<HttpServletRequest>(relaxed = true)
private val mockHttpResponse = mockk<HttpServletResponse>(relaxed = true)

class JobDescriptorServletsTest {

    @Before
    fun setup(){
        mockkStatic(Context::class)
        jobServlet =  myHttpServlet(mockContext)

    }

    @Test
    fun verify_Instance(){
        assertNotNull(jobServlet)
    }
    @Test
    fun doPostTest(){
        val protectedMethod = myHttpServlet::class.java.getDeclaredMethod("doPost")
        protectedMethod.isAccessible = true
        protectedMethod.invoke(jobServlet.doPost(mockHttpRequest, mockHttpResponse))


    }
}

Solution

  • You can use Kotlin's reflection instead of Java

    
        private val mapper = Mappers.getMapper(MyMapper::class.java)
        private val propertyMapper = Mappers.getMapper(PropertyMapper::class.java)
    
        private val service = EmployeeService(repository, mapper)
    
     @Test
     fun test() {
      // Arrange
            val property = mapper::class
                .memberProperties
                .first { it.javaField?.type == PropertyMapper::class.java }
                .also { it.isAccessible = true }
            if (property is KMutableProperty<*>) {
                property.setter.call(mapper, propertyMapper)
            }
            initializeContext()
    
    
            // Act & Assert
            val response = assertDoesNotThrow { service.someMethod() }
    
            assertAll(
                { Assertions.assertEquals(HttpStatus.OK, response.statusCode) },
                { assertNotNull(response.body?.data) },
                { response.body?.success?.let(Assertions::assertTrue) },
            )
    }