我试图在 JavaPoet api 中创建 TestSuite。我在 testClasses 中有我的 junit 类的列表,所以我想添加成员注释但 addmember 允许我们一次只添加一个对象,那么我如何添加所有列表?
.addAnnotation(AnnotationSpec.builder(SuiteClasses.class)
.addMember("value", "$T.class", testClasses.toArray()).build())
尝试为构建器提取变量。
AnnotationSpec.Builder ab = AnnotationSpec.builder(SuiteClasses.class);
for (String s : strings) {
ab.addMember(s, "$S", lookup(s));
}
AnnotationSpec annotation = ab.build();
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);
}
}