我想用Java CodeModel API
生成如下例子的代码package com.testcase.myPackage;
package com.aaa.abc;
package com.bbb.b;
import org.testng.annotations.Test;
public class TestCode {
private int a;
private int b;
@Test public void testMethod() throws excep1,excep2,excep3 {
a=abc.method1(b.param1,param2,param3);
}
}
我已经宣布了类变量a
& b
,带有@Test注释的方法testMethod。现在我陷入了以下几点:
无法在方法中抛出多个异常(抛出异常1,异常2,异常3)。
无法调用具有多个参数的方法&在类变量中分配该调用
a = abc.method1(b.param1, param2, param3)
如何解决这些问题?
答案 0 :(得分:0)
声明多个方法异常和多个方法调用参数JCodeModel的API允许您链接调用以添加异常和参数:
例外:
testMethod._throws(Exception1.class)._throws(Exception2.class)._throws(Exception3.class);
方法参数:
body.assign(a, abcRef.staticInvoke("method1").arg(param1Var).arg(param2Var).arg(param3Var));
为了完整起见,这里有一些代码来生成靠近你的例子的类:
JDefinedClass testCodeClass = codeModel._class(JMod.PUBLIC, "com.testcase.myPackage.TestCode", ClassType.CLASS);
JFieldVar a = testCodeClass.field(JMod.PRIVATE, codeModel.INT, "a");
JFieldVar b = testCodeClass.field(JMod.PRIVATE, codeModel.INT, "b");
JMethod testMethod = testCodeClass.method(JMod.PUBLIC, codeModel.VOID, "testMethod");
testMethod.annotate(Test.class);
testMethod._throws(Exception1.class)._throws(Exception2.class)._throws(Exception3.class);
JBlock body = testMethod.body();
JClass abcRef = codeModel.ref(abc.class);
JVar param1Var = body.decl(codeModel.INT, "param1", JExpr.lit(1));
JVar param2Var = body.decl(codeModel.INT, "param2", JExpr.lit(2));
JVar param3Var = body.decl(codeModel.INT, "param3", JExpr.lit(3));
body.assign(a, abcRef.staticInvoke("method1").arg(param1Var).arg(param2Var).arg(param3Var));
生成:
package com.testcase.myPackage;
import com.xxx.yyy.abc;
import org.junit.Test;
public class TestCode {
private int a;
private int b;
@Test
public void testMethod()
throws Exception1, Exception2, Exception3
{
int param1 = 1;
int param2 = 2;
int param3 = 3;
a = abc.method1(param1, param2, param3);
}
}