2016-09-01 98 views
0

我試圖在JavaPoet api中創建TestSuite。 我在testClasses中有我的junit類的列表,所以我想添加成員註釋,但addmember允許我們在時間只添加一個對象,所以如何添加所有列表?將成員添加到JavaPoet

.addAnnotation(AnnotationSpec.builder(SuiteClasses.class) 
.addMember("value", "$T.class", testClasses.toArray()).build()) 

回答

1

嘗試爲構建器提取變量。

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

看我的回答 –

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); 
    } 
}