我正在使用CodeModel 2.6。
当getType()方法从一个抽象超类继承时,我将如何生成这条指令,这两个级别高于JDefinedClass?
assertEquals(GeneraldocumenMetadata.TYPE, generaldocumenMetadata.getType());
背景:
最终结果/所需方法如下:
@Test
public void testParameterizedConstructorSuccess()
{
String modifiedType = GeneraldocumenMetadata.TYPE + "andMore";
generaldocumenMetadata = new GeneraldocumenMetadata(modifiedType);
assertEquals(modifiedType, generaldocumenMetadata.getType());
}
CodeModel方法目前看起来像这样,但是“definedClass.getMethod(”getType“,new JType [] {});”返回null
private void testDefaultConstructorMethod(JFieldVar uutField, JVar staticTYPEVar, final JDefinedClass unitTestClass, JDefinedClass definedClass, JCodeModel codeModel)
{
int modifiers = JMod.PUBLIC;
JMethod unitTestMethod = unitTestClass.method(modifiers, Void.TYPE, "testDefaultConstructor");
unitTestMethod.annotate(org.junit.Test.class);
JBlock unitTestBody = unitTestMethod.body();
unitTestBody.assign(uutField, JExpr._new(unitTestClass));
JClass abstractItemMetadataClass = definedClass._extends();
JMethod getTypeMethod = definedClass.getMethod("getType", new JType[] {});
JExpr.invoke(getTypeMethod);
JInvocation assertEqualsInvoke = codeModel.directClass("org.junit.Assert").staticInvoke("assertEquals").arg(staticTYPEVar).arg(JExpr.invoke(getTypeMethod));
unitTestBody.add(assertEqualsInvoke);
}
答案 0 :(得分:2)
您需要调用该方法,而不是获取它,因为codeModel不会解析您定义的类:
JExpr.invoke(uutField, "getType");
这意味着您的代码模型代码如下所示:
private void testDefaultConstructorMethod(JFieldVar uutField, JVar staticTYPEVar, final JDefinedClass unitTestClass, JDefinedClass definedClass, JCodeModel codeModel)
{
int modifiers = JMod.PUBLIC;
JMethod unitTestMethod = unitTestClass.method(modifiers, Void.TYPE, "testDefaultConstructor");
unitTestMethod.annotate(org.junit.Test.class);
JBlock unitTestBody = unitTestMethod.body();
unitTestBody.assign(uutField, JExpr._new(unitTestClass));
JClass abstractItemMetadataClass = definedClass._extends();
JInvocation assertEqualsInvoke = codeModel.ref(org.junit.Assert.class).staticInvoke("assertEquals").arg(staticTYPEVar).arg(JExpr.invoke(uutField, "getType"));
unitTestBody.add(assertEqualsInvoke);
}