Skip to content

Instantly share code, notes, and snippets.

@aoriani
Created April 15, 2018 04:05
Show Gist options
  • Save aoriani/8cef00e2499baa85a81155ec40a79bcd to your computer and use it in GitHub Desktop.
Save aoriani/8cef00e2499baa85a81155ec40a79bcd to your computer and use it in GitHub Desktop.
A simple implementation of a mock library
import net.sf.cglib.proxy.Enhancer
import net.sf.cglib.proxy.MethodInterceptor
import net.sf.cglib.proxy.MethodProxy
import org.hamcrest.core.Is.`is`
import org.junit.Assert.assertThat
import org.junit.Test
import java.lang.reflect.Method
import java.net.Socket
inline fun <reified T> createMock(interceptor: MethodInterceptor) = Enhancer().apply {
setSuperclass(T::class.java)
setCallback(interceptor)
}.create() as T
class SimpleMockitoTest {
private val mockedSocket = createMock<Socket>(MethodInterceptor { thiz: Any, method: Method, args: Array<Any?>, methodProxy: MethodProxy ->
when (method.name) {
"getLocalPort" -> 42
"getInputStream" -> "foo bar".byteInputStream()
"setSoTimeout" -> assertThat(args[0] as Int, `is`(70))
else -> throw UnsupportedOperationException(method.name)
}
})
@Test
fun testSocket() {
assertThat(mockedSocket.localPort, `is`(42))
assertThat(mockedSocket.getInputStream().bufferedReader().use { it.readText() }, `is`("foo bar"))
mockedSocket.soTimeout = 70
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment