add ByteCodeTestUtil

This commit is contained in:
simon 2024-06-22 22:27:15 +02:00
parent e4f5bbbfa9
commit 7b82840b3d
2 changed files with 40 additions and 4 deletions

View File

@ -0,0 +1,28 @@
import de.maishai.Compiler;
import java.lang.reflect.Method;
import java.util.List;
public class BytecodeTestUtil {
private Class<?> clazz;
public BytecodeTestUtil(String sourceFilePath, String className) throws Exception {
byte[] resultBytecode = Compiler.generateByteCodeArrayFromFile(List.of(sourceFilePath)).get(0);
ClassLoader classLoader = new ClassLoader() {
@Override
protected Class<?> findClass(String name) {
return defineClass(name, resultBytecode, 0, resultBytecode.length);
}
};
clazz = classLoader.loadClass(className);
}
public Object invokeMethod(String methodName, Class<?>[] parameterTypes, Object... args) throws Exception {
Object instance = clazz.getDeclaredConstructor().newInstance();
Method method = clazz.getMethod(methodName, parameterTypes);
return method.invoke(instance, args);
}
}

View File

@ -1,9 +1,6 @@
import de.maishai.Compiler;
import de.maishai.ast.records.Program;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CodegeneratorTests {
@ -13,4 +10,15 @@ public class CodegeneratorTests {
// byte[] resultBytecode = Compiler.generateByteCodeArrayFromTypedAst();
// assertEquals(AbstractSyntax_PublicClass.get(), resultBytecode);
// }
@Test
public void testMethodCall() {
assertDoesNotThrow(() -> {
BytecodeTestUtil testUtility = new BytecodeTestUtil("src/test/testFiles/JavaTestfilesFeatures/MethodCall.java", "MethodCall");
assertEquals(3, testUtility.invokeMethod("method", null));
assertEquals(1, testUtility.invokeMethod("method1", new Class<?>[]{int.class}, 1));
assertEquals(3, testUtility.invokeMethod("method2", new Class<?>[]{int.class, int.class}, 1, 2));
});
}
}