package net.pterodactylus.sone.test
-import org.junit.rules.*
-import java.lang.reflect.*
-
-private val modifiers = Field::class.java.getDeclaredField("modifiers").apply {
- isAccessible = true
-}
-
-fun setField(instance: Any, name: String, value: Any?) {
- generateSequence<Class<*>>(instance.javaClass) { it.superclass }
- .flatMap { it.declaredFields.asSequence() }
- .filter { it.name == name }
- .toList()
- .forEach { field ->
- field.isAccessible = true
- modifiers.setInt(field, field.modifiers and Modifier.FINAL.inv())
- field.set(instance, value)
- }
+import org.junit.rules.ExpectedException
+import sun.misc.Unsafe
+
+inline fun <reified O : Any> setField(instance: O, name: String, value: Any?) {
+ val field = O::class.java.getDeclaredField(name)
+ val unsafe = Unsafe::class.java.getDeclaredField("theUnsafe").apply {
+ isAccessible = true
+ }.get(null) as Unsafe
+ val offset = unsafe.objectFieldOffset(field)
+ unsafe.putObject(instance, offset, value)
}
inline fun <reified T : Throwable> ExpectedException.expect() = expect(T::class.java)
val request = deepMock<FreenetRequest>()
val pageMakerInteractionFactory = deepMock<PageMakerInteractionFactory>()
whenever(pageMakerInteractionFactory.createPageMaker(request.toadletContext, "page title").renderPage()).thenReturn("<page>")
- setField(page, "pageMakerInteractionFactory", pageMakerInteractionFactory)
+ setField<FreenetTemplatePage>(page, "pageMakerInteractionFactory", pageMakerInteractionFactory)
val response = page.handleRequest(request, Response(ByteArrayOutputStream()))
assertThat(response.statusCode, equalTo(200))
assertThat((response.content as ByteArrayOutputStream).toString(UTF_8.name()), equalTo("<page>"))