Skip to content

Instantly share code, notes, and snippets.

@bastienapp
Created June 14, 2019 23:18
Show Gist options
  • Save bastienapp/b98f5dc6e3e8f5f598c84d49f428aafa to your computer and use it in GitHub Desktop.
Save bastienapp/b98f5dc6e3e8f5f598c84d49f428aafa to your computer and use it in GitHub Desktop.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.util.Random;
import javassist.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.invoke.MethodHandles;
public class MainTest {
@Test
public void test1() {
Main math = new Main();
assertEquals(1, math.pow(2, 0));
}
@Test
public void test2() {
Main math = new Main();
assertEquals(2, math.pow(2, 1));
}
@Test
public void test4() {
Main math = new Main();
assertEquals(4, math.pow(2, 2));
}
@Test
public void test8() {
Main math = new Main();
assertEquals(8, math.pow(2, 3));
}
@Test
public void testRandom() {
Main math = new Main();
Random r = new Random();
int a = r.nextInt(10);
int b = r.nextInt(10);
assertEquals(Math.pow(a, b), math.pow(a, b), 0);
}
@Test
public void testRecusion() throws Exception {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.getAndRename("Main", "MainReflect");
CtField f = new CtField(CtClass.intType, "recursion", cc);
f.setModifiers(Modifier.PUBLIC);
cc.addField(f);
CtMethod m = cc.getDeclaredMethod("pow");
m.insertBefore("{ recursion++; }");
byte[] bytes = cc.toBytecode();
MethodHandles.Lookup lookup = MethodHandles.lookup();
Class<?> clazz = lookup.defineClass(bytes);
Object inst = clazz.getConstructor().newInstance();
Field field = clazz.getField("recursion");
field.set(inst, 0);
Method pow = clazz.getMethod("pow", int.class, int.class);
Random r = new Random();
final int a = r.nextInt(10);
final int b = 2 + r.nextInt(8);
long result = (long) pow.invoke(inst, a, b);
Object recursion = field.get(inst);
assertEquals((b + 1) + " recursions were expected", b + 1, (int) recursion);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment