提问人:Xuai 提问时间:9/13/2023 最后编辑:Xuai 更新时间:11/8/2023 访问量:82
如何在 Kotlin 上的单元测试中访问受保护的方法
how to access protected method inside unit test on kotlin
问:
有没有办法进入受保护的值并在 Kotlin 单元测试中访问它,下面是我的 doPost 保护方法,我尝试过反射,但它不起作用,遵循此示例 https://stackoverflow.com/a/41695398/6377156
@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))
}
}
答:
0赞
Bekzod
11/8/2023
#1
您可以使用 Kotlin 的反射而不是 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) },
)
}
评论