将成员添加到JavaPoet

时间:2016-09-01 11:18:16

标签: java junit javapoet

我尝试在JavaPoet api中创建TestSuite。 我在testClasses中有我的junit类的List,所以我想添加成员注释但是addmember允许我们一次只添加一个对象,那么我如何添加所有列表?

\K

2 个答案:

答案 0 :(得分:1)

尝试为构建器提取变量。

AnnotationSpec.Builder ab = AnnotationSpec.builder(SuiteClasses.class);
for (String s : strings) {
  ab.addMember(s, "$S", lookup(s));
}
AnnotationSpec annotation = ab.build();

答案 1 :(得分:0)

import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import org.junit.Test;

import javax.lang.model.element.Modifier;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Javapoet {

    public void generateTestSuite(List<Class> testClasses) throws IOException {
        MethodSpec test = MethodSpec.methodBuilder("test").addModifiers(Modifier.PUBLIC).returns(void.class)
                .addAnnotation(Test.class).build();

        TypeSpec testSuite = TypeSpec.classBuilder("TestSuite").addModifiers(Modifier.PUBLIC).addAnnotation(

                AnnotationSpec.Builder ab = AnnotationSpec.builder(SuiteClasses.class);
        for (String s : strings) {
            ab.addMember(s, "$S", lookup(s));
        }
        AnnotationSpec annotation = ab.build();


        JavaFile javaFile = JavaFile.builder("", testSuite).build();

        Path path = Paths.get("src/test/java");
        javaFile.writeTo(path);
    }
}