2

我正在使用 CodeModel 2.6。

当 getType() 方法继承自抽象超类时,我将如何生成这条指令,比 JDefinedClass 高两层?

    assertEquals(GeneraldocumenMetadata.TYPE, generaldocumenMetadata.getType());

背景:

  1. assertEquals(...) 方法来自“import static org.junit.Assert.assertEquals;”
  2. 类层次结构是
    • GeneraldocumenMetadata 扩展了 ItemMetadata
    • ItemMetadata 扩展 AbstractItemMetadata
    • AbstractItemMetadata 拥有 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);
}
4

1 回答 1

2

您需要调用该方法,而不是获取它,因为 codeModel 不会解析您定义的类:

JExpr.invoke(uutField, "getType");

这意味着您的 codemodel 代码将如下所示:

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);
}
于 2013-12-03T19:04:30.173 回答