KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > junit > AbstractTestGenerator


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.junit;
21
22 import com.sun.source.tree.BlockTree;
23 import com.sun.source.tree.ClassTree;
24 import com.sun.source.tree.CompilationUnitTree;
25 import com.sun.source.tree.ExpressionTree;
26 import com.sun.source.tree.IdentifierTree;
27 import com.sun.source.tree.LiteralTree;
28 import com.sun.source.tree.MethodInvocationTree;
29 import com.sun.source.tree.MethodTree;
30 import com.sun.source.tree.ModifiersTree;
31 import com.sun.source.tree.StatementTree;
32 import com.sun.source.tree.Tree;
33 import com.sun.source.tree.TypeParameterTree;
34 import com.sun.source.tree.VariableTree;
35 import com.sun.source.util.TreePath;
36 import java.io.IOException JavaDoc;
37 import java.util.ArrayList JavaDoc;
38 import java.util.Collections JavaDoc;
39 import java.util.EnumSet JavaDoc;
40 import java.util.HashSet JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.List JavaDoc;
43 import java.util.Set JavaDoc;
44 import java.util.logging.Level JavaDoc;
45 import java.util.logging.Logger JavaDoc;
46 import javax.lang.model.element.Element;
47 import javax.lang.model.element.ElementKind;
48 import javax.lang.model.element.ExecutableElement;
49 import javax.lang.model.element.Modifier;
50 import javax.lang.model.element.TypeElement;
51 import javax.lang.model.element.VariableElement;
52 import javax.lang.model.type.TypeKind;
53 import javax.lang.model.type.TypeMirror;
54 import javax.lang.model.util.ElementFilter;
55 import javax.lang.model.util.Types;
56 import org.netbeans.api.java.source.CancellableTask;
57 import org.netbeans.api.java.source.ClasspathInfo;
58 import org.netbeans.api.java.source.Comment;
59 import org.netbeans.api.java.source.CompilationInfo;
60 import org.netbeans.api.java.source.ElementHandle;
61 import org.netbeans.api.java.source.JavaSource.Phase;
62 import org.netbeans.api.java.source.TreeMaker;
63 import org.netbeans.api.java.source.WorkingCopy;
64 import org.openide.util.NbBundle;
65 import static javax.lang.model.element.Modifier.ABSTRACT;
66 import static javax.lang.model.element.Modifier.PUBLIC;
67 import static javax.lang.model.element.Modifier.PRIVATE;
68 import static javax.lang.model.element.Modifier.PROTECTED;
69 import static javax.lang.model.element.Modifier.STATIC;
70 import static org.netbeans.modules.junit.TestCreator.ACCESS_MODIFIERS;
71
72 /**
73  *
74  * @author Marian Petras
75  */

76 abstract class AbstractTestGenerator implements CancellableTask<WorkingCopy>{
77     
78     /**
79      * name of the 'instance' variable in the generated test method skeleton
80      *
81      * @see #RESULT_VAR_NAME
82      * @see #EXP_RESULT_VAR_NAME
83      */

84     private static final String JavaDoc INSTANCE_VAR_NAME = "instance"; //NOI18N
85
/**
86      * name of the 'result' variable in the generated test method skeleton
87      *
88      * @see #EXP_RESULT_VAR_NAME
89      */

90     private static final String JavaDoc RESULT_VAR_NAME = "result"; //NOI18N
91
/**
92      * name of the 'expected result' variable in the generated test method
93      * skeleton
94      *
95      * @see #RESULT_VAR_NAME
96      */

97     private static final String JavaDoc EXP_RESULT_VAR_NAME = "expResult"; //NOI18N
98
/**
99      * base for artificial names of variables
100      * (if there is no name to derive from)
101      */

102     private static final String JavaDoc ARTIFICAL_VAR_NAME_BASE = "arg"; //NOI18N
103
/** */
104     private static final EnumSet JavaDoc<Modifier> NO_MODIFIERS
105             = EnumSet.noneOf(Modifier.class);
106     
107     /**
108      * Returns {@code EnumSet} of all access modifiers.
109      *
110      * @return {@code EnumSet} of all access modifiers;
111      * it is guaranteed that the returned set always contains
112      * the same set of {@code Modifier}s, but the returned
113      * instance may not always be the same
114      */

115     protected static EnumSet JavaDoc<Modifier> accessModifiers() {
116         /*
117          * An alternative would be to create an instance of
118          * unmodifiable Set<Modifier> (e.g. Collections.unmodifiableSet(...))
119          * and always return this instance. But the instance would not be an
120          * instance of (subclass of) EnumSet which would significantly slow down
121          * many operations performed on it.
122          */

123         return EnumSet.copyOf(ACCESS_MODIFIERS);
124     }
125     
126     /**
127      * Returns an empty {@code EnumSet} of {@code Modifier}s.
128      *
129      * @return empty {@code EnumSet} of all {@code Modifier}s;
130      * it is guaranteed that the returned set is always empty
131      * but the returned instance may not always be the same
132      */

133     protected static EnumSet JavaDoc<Modifier> noModifiers() {
134         /*
135          * An alternative would be to create an instance of
136          * unmodifiable Set<Modifier> (e.g. Collections.<Modifier>emptySet())
137          * and always return that instance. But the instance would not be an
138          * instance of (subclass of) EnumSet which would significantly slow down
139          * many operations performed on it.
140          */

141         return EnumSet.copyOf(NO_MODIFIERS);
142     }
143     
144     /** */
145     protected final TestGeneratorSetup setup;
146
147     private final List JavaDoc<ElementHandle<TypeElement>> srcTopClassElemHandles;
148
149     private final List JavaDoc<String JavaDoc> suiteMembers;
150
151     private final boolean isNewTestClass;
152
153     private List JavaDoc<String JavaDoc>processedClassNames;
154
155     /**
156      * cached value of <code>JUnitSettings.getGenerateMainMethodBody()</code>
157      */

158     private String JavaDoc initialMainMethodBody;
159     
160     private volatile boolean cancelled = false;
161
162
163     /**
164      * Used when creating a new empty test class.
165      */

166     protected AbstractTestGenerator(TestGeneratorSetup setup) {
167         this.setup = setup;
168         this.srcTopClassElemHandles = null;
169         this.suiteMembers = null;
170         this.isNewTestClass = true; //value not used
171
}
172
173     /**
174      * Used when creating a test class for a given source class
175      * or when creating a test suite.
176      */

177     protected AbstractTestGenerator(
178                     TestGeneratorSetup setup,
179                     List JavaDoc<ElementHandle<TypeElement>> srcTopClassHandles,
180                     List JavaDoc<String JavaDoc>suiteMembers,
181                     boolean isNewTestClass) {
182         this.setup = setup;
183         this.srcTopClassElemHandles = srcTopClassHandles;
184         this.suiteMembers = suiteMembers;
185         this.isNewTestClass = isNewTestClass;
186     }
187
188     /**
189      */

190     public void run(WorkingCopy workingCopy) throws IOException JavaDoc {
191         
192         workingCopy.toPhase(Phase.ELEMENTS_RESOLVED);
193
194         CompilationUnitTree compUnit = workingCopy.getCompilationUnit();
195         List JavaDoc<ClassTree> tstTopClasses = TopClassFinder.findTopClasses(
196                                             compUnit,
197                                             workingCopy.getTreeUtilities());
198         TreePath compUnitPath = new TreePath(compUnit);
199
200         List JavaDoc<TypeElement> srcTopClassElems
201                 = resolveHandles(workingCopy, srcTopClassElemHandles);
202
203         if ((srcTopClassElems != null) && !srcTopClassElems.isEmpty()) {
204
205             final String JavaDoc className
206                     = workingCopy.getClasspathInfo()
207                       .getClassPath(ClasspathInfo.PathKind.SOURCE)
208                       .getResourceName(workingCopy.getFileObject(), '.', false);
209
210             /* Create/update a test class for each testable source class: */
211             for (TypeElement srcTopClass : srcTopClassElems) {
212                 createOrUpdateTestClass(srcTopClass,
213                                         tstTopClasses,
214                                         className,
215                                         compUnitPath,
216                                         workingCopy);
217             }
218         } else if (suiteMembers != null) { //test suite
219
for (ClassTree tstClass : tstTopClasses) {
220                 TreePath tstClassTreePath = new TreePath(compUnitPath,
221                                                          tstClass);
222                 ClassTree origTstTopClass = tstClass;
223                 ClassTree tstTopClass = generateMissingSuiteClassMembers(
224                                                 tstClass,
225                                                 tstClassTreePath,
226                                                 suiteMembers,
227                                                 isNewTestClass,
228                                                 workingCopy);
229                 if (tstTopClass != origTstTopClass) {
230                     workingCopy.rewrite(origTstTopClass,
231                                         tstTopClass);
232                 }
233                 classProcessed(tstClass);
234             }
235         } else if (srcTopClassElems == null) { //new empty test class
236
for (ClassTree tstClass : tstTopClasses) {
237                 ClassTree origTstTopClass = tstClass;
238                 ClassTree tstTopClass = generateMissingInitMembers(
239                                                 tstClass,
240                                                 new TreePath(compUnitPath,
241                                                              tstClass),
242                                                 workingCopy);
243                 if (tstTopClass != origTstTopClass) {
244                     workingCopy.rewrite(origTstTopClass,
245                                         tstTopClass);
246                 }
247             }
248         }
249     }
250     
251     /**
252      */

253     private void createOrUpdateTestClass(TypeElement srcTopClass,
254                                          List JavaDoc<ClassTree> tstTopClasses,
255                                          String JavaDoc testClassName,
256                                          TreePath compUnitPath,
257                                          WorkingCopy workingCopy) {
258         String JavaDoc srcClassName = srcTopClass.getSimpleName().toString();
259         String JavaDoc tstClassName = TestUtil.getTestClassName(srcClassName);
260
261         List JavaDoc<ExecutableElement> srcMethods
262                                 = findTestableMethods(srcTopClass);
263         boolean srcHasTestableMethods = !srcMethods.isEmpty();
264
265         ClassTree tstTopClass = null;
266         for (ClassTree tstClass : tstTopClasses) {
267             if (tstClass.getSimpleName().contentEquals(tstClassName)) {
268                 tstTopClass = tstClass;
269                 break;
270             }
271         }
272         
273         if (tstTopClass != null) {
274             TreePath tstTopClassTreePath = new TreePath(compUnitPath,
275                                                         tstTopClass);
276
277             ClassTree origTstTopClass = tstTopClass;
278             if (srcHasTestableMethods) {
279                 tstTopClass = generateMissingTestMethods(
280                                        srcTopClass,
281                                        srcMethods,
282                                        tstTopClass,
283                                        tstTopClassTreePath,
284                                        isNewTestClass,
285                                        workingCopy);
286             } else if (isNewTestClass) {
287                 tstTopClass = generateMissingInitMembers(
288                                         tstTopClass,
289                                         tstTopClassTreePath,
290                                         workingCopy);
291             }
292             if (tstTopClass != origTstTopClass) {
293                 workingCopy.rewrite(origTstTopClass,
294                                     tstTopClass);
295             }
296         } else {
297             if (srcHasTestableMethods
298                     || tstClassName.equals(TestUtil.getSimpleName(testClassName))) {
299                 tstTopClass = generateNewTestClass(workingCopy,
300                                                    tstClassName,
301                                                    srcTopClass,
302                                                    srcMethods);
303                 //PENDING - add the top class to the CompilationUnit
304

305                 //PENDING - generate suite method
306
}
307         }
308     }
309
310     /**
311      */

312     private ClassTree generateNewTestClass(WorkingCopy workingCopy,
313                                            String JavaDoc name,
314                                            TypeElement srcClass,
315                                            List JavaDoc<ExecutableElement> srcMethods) {
316         List JavaDoc<? extends Tree> initMembers = generateInitMembers(workingCopy);
317         List JavaDoc<MethodTree> testMethods = generateTestMethods(srcClass,
318                                                            srcMethods,
319                                                            workingCopy);
320         List JavaDoc<? extends Tree> members;
321         if (initMembers.isEmpty() && testMethods.isEmpty()) {
322             members = Collections.<Tree>emptyList();
323         } else if (initMembers.isEmpty()) {
324             members = testMethods;
325         } else if (testMethods.isEmpty()) {
326             members = initMembers;
327         } else {
328             List JavaDoc<Tree> allMembers = new ArrayList JavaDoc<Tree>(
329                                 initMembers.size() + testMethods.size());
330             allMembers.addAll(initMembers);
331             allMembers.addAll(testMethods);
332
333             members = allMembers;
334         }
335
336         return composeNewTestClass(workingCopy, name, members);
337     }
338
339     /**
340      */

341     protected abstract ClassTree composeNewTestClass(
342                                         WorkingCopy workingCopy,
343                                         String JavaDoc name,
344                                         List JavaDoc<? extends Tree> members);
345
346     /**
347      */

348     protected abstract List JavaDoc<? extends Tree> generateInitMembers(WorkingCopy workingCopy);
349
350     /**
351      */

352     protected abstract ClassTree generateMissingInitMembers(
353                                                 ClassTree tstClass,
354                                                 TreePath tstClassTreePath,
355                                                 WorkingCopy workingCopy);
356     
357     /**
358      */

359     protected abstract boolean generateMissingInitMembers(
360                                                  List JavaDoc<Tree> tstMembers,
361                                                  ClassMap clsMap,
362                                                  WorkingCopy workingCopy);
363     
364     /**
365      * Finds position for the first init method.
366      *
367      * @return index where the first init method should be put,
368      * or {@code -1} if the method should be put to the end
369      * of the class
370      */

371     protected int getPlaceForFirstInitMethod(ClassMap clsMap) {
372         int targetIndex;
373         if (clsMap.containsMethods()) {
374             targetIndex = clsMap.getFirstMethodIndex();
375         } else if (clsMap.containsInitializers()) {
376             targetIndex = clsMap.getLastInitializerIndex() + 1;
377         } else if (clsMap.containsNestedClasses()) {
378             targetIndex = clsMap.getFirstNestedClassIndex();
379         } else {
380             targetIndex = -1; //end of the class
381
}
382         return targetIndex;
383     }
384
385     /**
386      *
387      * @param srcMethods methods to create/update tests for
388      *
389      */

390     protected ClassTree generateMissingTestMethods(
391                                     TypeElement srcClass,
392                                     List JavaDoc<ExecutableElement> srcMethods,
393                                     ClassTree tstClass,
394                                     TreePath tstClassTreePath,
395                                     boolean generateMissingInitMembers,
396                                     WorkingCopy workingCopy) {
397         if (srcMethods.isEmpty()) {
398             return tstClass;
399         }
400
401         ClassMap clsMap = ClassMap.forClass(tstClass,
402                                             tstClassTreePath,
403                                             workingCopy.getTrees());
404
405         List JavaDoc<? extends Tree> tstMembersOrig = tstClass.getMembers();
406         List JavaDoc<Tree> tstMembers = new ArrayList JavaDoc<Tree>(tstMembersOrig.size() + 4);
407         tstMembers.addAll(tstMembersOrig);
408
409         if (generateMissingInitMembers) {
410             generateMissingInitMembers(tstMembers, clsMap,
411                                        workingCopy);
412         }
413         generateMissingPostInitMethods(tstClassTreePath,
414                                          tstMembers,
415                                          clsMap,
416                                          workingCopy);
417
418         Boolean JavaDoc useNoArgConstrutor = null;
419         for (ExecutableElement srcMethod : srcMethods) {
420             String JavaDoc testMethodName = createTestMethodName(
421                                     srcMethod.getSimpleName().toString());
422             int testMethodIndex = clsMap.findNoArgMethod(testMethodName);
423             if (testMethodIndex != -1) {
424                 continue; //corresponding test method already exists
425
}
426
427             if (useNoArgConstrutor == null) {
428                 useNoArgConstrutor = Boolean.valueOf(
429                               hasAccessibleNoArgConstructor(srcClass));
430             }
431             MethodTree newTestMethod = generateTestMethod(
432                             srcClass,
433                             srcMethod,
434                             useNoArgConstrutor.booleanValue(),
435                             workingCopy);
436
437             tstMembers.add(newTestMethod);
438             clsMap.addNoArgMethod(newTestMethod.getName().toString());
439         }
440
441         if (tstMembers.size() == tstMembersOrig.size()) { //no test method added
442
return tstClass;
443         }
444
445         ClassTree newClass = workingCopy.getTreeMaker().Class(
446                 tstClass.getModifiers(),
447                 tstClass.getSimpleName(),
448                 tstClass.getTypeParameters(),
449                 tstClass.getExtendsClause(),
450                 (List JavaDoc<? extends ExpressionTree>) tstClass.getImplementsClause(),
451                 tstMembers);
452         return newClass;
453     }
454     
455     /**
456      */

457     protected abstract void generateMissingPostInitMethods(
458                                                 TreePath tstClassTreePath,
459                                                 List JavaDoc<Tree> tstMembers,
460                                                 ClassMap clsMap,
461                                                 WorkingCopy workingCopy);
462     
463     /**
464      */

465     private List JavaDoc<MethodTree> generateTestMethods(
466                                        TypeElement srcClass,
467                                        List JavaDoc<ExecutableElement> srcMethods,
468                                        WorkingCopy workingCopy) {
469         if (srcMethods.isEmpty()) {
470             return Collections.<MethodTree>emptyList();
471         }
472
473         boolean useNoArgConstrutor = hasAccessibleNoArgConstructor(srcClass);
474         List JavaDoc<MethodTree> testMethods = new ArrayList JavaDoc<MethodTree>(srcMethods.size());
475         for (ExecutableElement srcMethod : srcMethods) {
476             testMethods.add(
477                     generateTestMethod(srcClass,
478                                        srcMethod,
479                                        useNoArgConstrutor,
480                                        workingCopy));
481         }
482         return testMethods;
483     }
484
485     /**
486      */

487     protected MethodTree generateTestMethod(TypeElement srcClass,
488                                           ExecutableElement srcMethod,
489                                           boolean useNoArgConstructor,
490                                           WorkingCopy workingCopy) {
491         final TreeMaker maker = workingCopy.getTreeMaker();
492
493         String JavaDoc testMethodName = createTestMethodName(
494                                     srcMethod.getSimpleName().toString());
495         ModifiersTree modifiers = maker.Modifiers(createModifierSet(PUBLIC));
496         List JavaDoc<ExpressionTree> throwsList;
497         if (throwsNonRuntimeExceptions(workingCopy, srcMethod)) {
498             throwsList = Collections.<ExpressionTree>singletonList(
499                                     maker.Identifier("Exception")); //NOI18N
500
} else {
501             throwsList = Collections.<ExpressionTree>emptyList();
502         }
503
504         MethodTree method = composeNewTestMethod(
505                 testMethodName,
506                 generateTestMethodBody(srcClass, srcMethod, useNoArgConstructor,
507                                        workingCopy),
508                 throwsList,
509                 workingCopy);
510
511         if (setup.isGenerateMethodJavadoc()) {
512             Comment javadoc = Comment.create(
513                 NbBundle.getMessage(
514                     TestCreator.class,
515                     "TestCreator.variantMethods.JavaDoc.comment", //NOI18N
516
srcMethod.getSimpleName().toString(),
517                     srcClass.getSimpleName().toString()));
518             maker.addComment(method, javadoc, false);
519         }
520
521         return method;
522     }
523     
524     /**
525      */

526     protected String JavaDoc createTestMethodName(String JavaDoc smName) {
527         return "test" //NOI18N
528
+ smName.substring(0,1).toUpperCase() + smName.substring(1);
529     }
530     
531     /**
532      */

533     protected abstract MethodTree composeNewTestMethod(
534                                             String JavaDoc testMethodName,
535                                             BlockTree testMethodBody,
536                                             List JavaDoc<ExpressionTree> throwsList,
537                                             WorkingCopy workingCopy);
538
539     /**
540      */

541     private ClassTree generateMissingSuiteClassMembers(
542                                             ClassTree tstClass,
543                                             TreePath tstClassTreePath,
544                                             List JavaDoc<String JavaDoc> suiteMembers,
545                                             boolean isNewTestClass,
546                                             WorkingCopy workingCopy) {
547         final TreeMaker maker = workingCopy.getTreeMaker();
548
549         List JavaDoc<? extends Tree> tstMembersOrig = tstClass.getMembers();
550         List JavaDoc<Tree> tstMembers = new ArrayList JavaDoc<Tree>(tstMembersOrig.size() + 2);
551         tstMembers.addAll(tstMembersOrig);
552         boolean membersChanged = false;
553
554         ClassMap classMap = ClassMap.forClass(tstClass,
555                                               tstClassTreePath,
556                                               workingCopy.getTrees());
557
558         if (isNewTestClass) {
559             membersChanged |= generateMissingInitMembers(tstMembers,
560                                                          classMap,
561                                                          workingCopy);
562         }
563
564         return finishSuiteClass(tstClass,
565                                 tstClassTreePath,
566                                 tstMembers,
567                                 suiteMembers,
568                                 membersChanged,
569                                 classMap,
570                                 workingCopy);
571     }
572     
573     /**
574      */

575     protected abstract ClassTree finishSuiteClass(
576                                         ClassTree tstClass,
577                                         TreePath tstClassTreePath,
578                                         List JavaDoc<Tree> tstMembers,
579                                         List JavaDoc<String JavaDoc> suiteMembers,
580                                         boolean membersChanged,
581                                         ClassMap classMap,
582                                         WorkingCopy workingCopy);
583     
584     // <editor-fold defaultstate="collapsed" desc=" disabled code ">
585
// /**
586
// */
587
// private void addMainMethod(final ClassTree classTree) {
588
// MethodTree mainMethod = createMainMethod(maker);
589
// if (mainMethod != null) {
590
// maker.addClassMember(classTree, mainMethod);
591
// }
592
// }
593
//
594
// /**
595
// */
596
// private void fillTestClass(JavaClass srcClass, JavaClass tstClass) {
597
//
598
// fillGeneral(tstClass);
599
//
600
// List innerClasses = TestUtil.filterFeatures(srcClass,
601
// JavaClass.class);
602
//
603
// /* Create test classes for inner classes: */
604
// for (Iterator i = innerClasses.iterator(); i.hasNext(); ) {
605
// JavaClass innerCls = (JavaClass) i.next();
606
//
607
// if (!isClassTestable(innerCls).isTestable()) {
608
// continue;
609
// }
610
//
611
// /*
612
// * Check whether the test class for the inner class exists
613
// * and create one if it does not exist:
614
// */
615
// String innerTestClsName
616
// = TestUtil.getTestClassName(innerCls.getSimpleName());
617
// JavaClass innerTestCls
618
// = TestUtil.getClassBySimpleName(tstClass,
619
// innerTestClsName);
620
// if (innerTestCls == null) {
621
// innerTestCls = tgtPkg.getJavaClass().createJavaClass();
622
// innerTestCls.setSimpleName(
623
// tstClass.getName() + '.' + innerTestClsName);
624
// tstClass.getFeatures().add(innerTestCls);
625
// }
626
//
627
// /* Process the tested inner class: */
628
// fillTestClass(innerCls, innerTestCls);
629
//
630
// /* Make the inner test class testable with JUnit: */
631
// innerTestCls.setModifiers(innerTestCls.getModifiers() | Modifier.STATIC);
632
// }
633
//
634
// /* Add the suite() method (only if we are supposed to do so): */
635
// if (generateSuiteClasses && !hasSuiteMethod(tstClass)) {
636
// tstClass.getFeatures().add(createTestClassSuiteMethod(tstClass));
637
// }
638
//
639
// /* Create missing test methods: */
640
// List srcMethods = TestUtil.filterFeatures(srcClass, Method.class);
641
// for (Iterator i = srcMethods.iterator(); i.hasNext(); ) {
642
// Method sm = (Method) i.next();
643
// if (isMethodAcceptable(sm) &&
644
// tstClass.getMethod(createTestMethodName(sm.getName()),
645
// Collections.EMPTY_LIST,
646
// false)
647
// == null) {
648
// Method tm = createTestMethod(srcClass, sm);
649
// tstClass.getFeatures().add(tm);
650
// }
651
// }
652
//
653
// /* Create abstract class implementation: */
654
// if (!skipAbstractClasses
655
// && (Modifier.isAbstract(srcClass.getModifiers())
656
// || srcClass.isInterface())) {
657
// createAbstractImpl(srcClass, tstClass);
658
// }
659
// }
660
// </editor-fold>
661

662     // <editor-fold defaultstate="collapsed" desc=" disabled code ">
663
// /**
664
// */
665
// private Constructor createTestConstructor(String className) {
666
// Constructor constr = tgtPkg.getConstructor().createConstructor(
667
// className, // name
668
// Collections.EMPTY_LIST, // annotations
669
// Modifier.PUBLIC, // modifiers
670
// null, // Javadoc text
671
// null, // Javadoc - object
672
// null, // body - object
673
// "super(testName);\n", // body - text //NOI18N
674
// Collections.EMPTY_LIST, // type parameters
675
// createTestConstructorParams(), // parameters
676
// null); // exception names
677
// return constr;
678
// }
679
//
680
// /**
681
// */
682
// private List/*<Parameter>*/ createTestConstructorParams() {
683
// Parameter param = tgtPkg.getParameter().createParameter(
684
// "testName", // parameter name
685
// Collections.EMPTY_LIST, // annotations
686
// false, // not final
687
// TestUtil.getTypeReference( // type
688
// tgtPkg, "String"), //NOI18N
689
// 0, // dimCount
690
// false); // is not var.arg.
691
// return Collections.singletonList(param);
692
// }
693
// </editor-fold>
694

695     /**
696      * Creates a public static {@code main(String[])} method
697      * with the body taken from settings.
698      *
699      * @param maker {@code TreeMaker} to use for creating the method
700      * @return created {@code main(...)} method,
701      * or {@code null} if the method body would be empty
702      */

703     private MethodTree createMainMethod(TreeMaker maker) {
704         String JavaDoc initialMainMethodBody = getInitialMainMethodBody();
705         if (initialMainMethodBody.length() == 0) {
706             return null;
707         }
708
709         ModifiersTree modifiers = maker.Modifiers(
710                 createModifierSet(Modifier.PUBLIC, Modifier.STATIC));
711         VariableTree param = maker.Variable(
712                         maker.Modifiers(Collections.<Modifier>emptySet()),
713                         "argList", //NOI18N
714
maker.Identifier("String[]"), //NOI18N
715
null); //initializer - not used in params
716
MethodTree mainMethod = maker.Method(
717               modifiers, //public static
718
"main", //method name "main"//NOI18N
719
maker.PrimitiveType(TypeKind.VOID), //return type "void"
720
Collections.<TypeParameterTree>emptyList(), //type params
721
Collections.<VariableTree>singletonList(param), //method param
722
Collections.<ExpressionTree>emptyList(), //throws-list
723
'{' + initialMainMethodBody + '}', //body text
724
null); //only for annotations
725

726         return mainMethod;
727     }
728
729     // <editor-fold defaultstate="collapsed" desc=" disabled code ">
730
// /**
731
// */
732
// private void createAbstractImpl(JavaClass srcClass,
733
// JavaClass tstClass) {
734
// String implClassName = srcClass.getSimpleName() + "Impl"; //NOI18N
735
// JavaClass innerClass = tstClass.getInnerClass(implClassName, false);
736
//
737
// if (innerClass == null) {
738
// String javadocText =
739
// generateMethodJavadoc
740
// ? javadocText = NbBundle.getMessage(
741
// TestCreator.class,
742
// "TestCreator.abstracImpl.JavaDoc.comment",//NOI18N
743
// srcClass.getName())
744
// : null;
745
//
746
// // superclass
747
// MultipartId supClass
748
// = tgtPkg.getMultipartId().createMultipartId(
749
// srcClass.isInner() ? srcClass.getName()
750
// : srcClass.getSimpleName(),
751
// null,
752
// Collections.EMPTY_LIST);
753
//
754
// innerClass = tgtPkg.getJavaClass().createJavaClass(
755
// implClassName, // class name
756
// Collections.EMPTY_LIST, // annotations
757
// Modifier.PRIVATE, // modifiers
758
// javadocText, // Javadoc text
759
// null, // Javadoc - object
760
// Collections.EMPTY_LIST, // contents
761
// null, // super class name
762
// Collections.EMPTY_LIST, // interface names
763
// Collections.EMPTY_LIST);// type parameters
764
//
765
// if (srcClass.isInterface()) {
766
// innerClass.getInterfaceNames().add(supClass);
767
// } else {
768
// innerClass.setSuperClassName(supClass);
769
// }
770
//
771
// createImpleConstructors(srcClass, innerClass);
772
// tstClass.getFeatures().add(innerClass);
773
// }
774
//
775
// // created dummy implementation for all abstract methods
776
// List abstractMethods = TestUtil.collectFeatures(
777
// srcClass,
778
// Method.class,
779
// Modifier.ABSTRACT,
780
// true);
781
// for (Iterator i = abstractMethods.iterator(); i.hasNext(); ) {
782
// Method oldMethod = (Method) i.next();
783
// if (innerClass.getMethod(
784
// oldMethod.getName(),
785
// TestUtil.getParameterTypes(oldMethod.getParameters()),
786
// false) == null) {
787
// Method newMethod = createMethodImpl(oldMethod);
788
// innerClass.getFeatures().add(newMethod);
789
// }
790
//
791
// }
792
// }
793
//
794
// /**
795
// */
796
// private void createImpleConstructors(JavaClass srcClass,
797
// JavaClass tgtClass) {
798
// List constructors = TestUtil.filterFeatures(srcClass,
799
// Constructor.class);
800
// for (Iterator i = constructors.iterator(); i.hasNext(); ) {
801
// Constructor ctr = (Constructor) i.next();
802
//
803
// if (Modifier.isPrivate(ctr.getModifiers())) {
804
// continue;
805
// }
806
//
807
// Constructor nctr = tgtPkg.getConstructor().createConstructor();
808
// nctr.setBodyText("super(" //NOI18N
809
// + getParameterString(ctr.getParameters())
810
// + ");\n"); //NOI18N
811
// nctr.getParameters().addAll(
812
// TestUtil.cloneParams(ctr.getParameters(), tgtPkg));
813
// tgtClass.getFeatures().add(nctr);
814
// }
815
// }
816
//
817
// /**
818
// */
819
// private Method createMethodImpl(Method origMethod) {
820
// Method newMethod = tgtPkg.getMethod().createMethod();
821
//
822
// newMethod.setName(origMethod.getName());
823
//
824
// /* Set modifiers of the method: */
825
// int mod = origMethod.getModifiers() & ~Modifier.ABSTRACT;
826
// if (((JavaClass) origMethod.getDeclaringClass()).isInterface()) {
827
// mod |= Modifier.PUBLIC;
828
// }
829
// newMethod.setModifiers(mod);
830
//
831
// // prepare the body of method implementation
832
// StringBuffer body = new StringBuffer(200);
833
// if (generateSourceCodeHints) {
834
// body.append(NbBundle.getMessage(
835
// TestCreator.class,
836
// "TestCreator.methodImpl.bodyComment")); //NOI18N
837
// body.append("\n\n"); //NOI18N
838
// }
839
//
840
// newMethod.setType(origMethod.getType());
841
// Type type = origMethod.getType();
842
// if (type != null) {
843
// String value = null;
844
// if ((type instanceof JavaClass) || (type instanceof Array)) {
845
// value = "null"; //NOI18N
846
// } else if (type instanceof PrimitiveType) {
847
// PrimitiveTypeKindEnum tke = (PrimitiveTypeKindEnum)
848
// ((PrimitiveType) type).getKind();
849
// if (tke.equals(PrimitiveTypeKindEnum.BOOLEAN)) {
850
// value = "false"; //NOI18N
851
// } else if (!tke.equals(PrimitiveTypeKindEnum.VOID)) {
852
// value = "0"; //NOI18N
853
// }
854
// }
855
//
856
// if (value != null) {
857
// body.append("return ").append(value).append(";\n"); //NOI18N
858
// }
859
// }
860
//
861
// newMethod.setBodyText(body.toString());
862
//
863
// // parameters
864
// newMethod.getParameters().addAll(
865
// TestUtil.cloneParams(origMethod.getParameters(), tgtPkg));
866
//
867
// return newMethod;
868
// }
869
//
870
// /**
871
// */
872
// private String generateJavadoc(JavaClass srcClass, Method srcMethod) {
873
// return NbBundle.getMessage(
874
// TestCreator.class,
875
// "TestCreator.variantMethods.JavaDoc.comment", //NOI18N
876
// srcMethod.getName(),
877
// srcClass.getName());
878
// }
879
// </editor-fold>
880

881     /**
882      */

883     protected BlockTree generateTestMethodBody(TypeElement srcClass,
884                                                ExecutableElement srcMethod,
885                                                boolean useNoArgConstructor,
886                                                WorkingCopy workingCopy) {
887         TreeMaker maker = workingCopy.getTreeMaker();
888
889         boolean isStatic = srcMethod.getModifiers().contains(Modifier.STATIC);
890         List JavaDoc<StatementTree> statements = new ArrayList JavaDoc<StatementTree>(8);
891
892         if (setup.isGenerateDefMethodBody()) {
893             StatementTree sout = generateSystemOutPrintln(
894                                     maker,
895                                     srcMethod.getSimpleName().toString());
896             List JavaDoc<VariableTree> paramVariables = generateParamVariables(
897                                     maker,
898                                     srcMethod);
899             statements.add(sout);
900             statements.addAll(paramVariables);
901
902             if (!isStatic) {
903                 VariableTree instanceVarInit = maker.Variable(
904                         maker.Modifiers(Collections.<Modifier>emptySet()),
905                         INSTANCE_VAR_NAME,
906                         maker.QualIdent(srcClass),
907                         useNoArgConstructor
908                              ? generateNoArgConstructorCall(maker, srcClass)
909                              : maker.Literal(null));
910                 statements.add(instanceVarInit);
911             }
912
913             MethodInvocationTree methodCall = maker.MethodInvocation(
914                     Collections.<ExpressionTree>emptyList(), //type args.
915
maker.MemberSelect(
916                             isStatic ? maker.QualIdent(srcClass)
917                                      : maker.Identifier(INSTANCE_VAR_NAME),
918                             srcMethod.getSimpleName()),
919                     createIdentifiers(maker, paramVariables));
920
921             TypeMirror retType = srcMethod.getReturnType();
922             TypeKind retTypeKind = retType.getKind();
923
924             if (retTypeKind == TypeKind.VOID) {
925                 StatementTree methodCallStmt = maker.ExpressionStatement(methodCall);
926
927                 statements.add(methodCallStmt);
928             } else {
929                 ExpressionTree retTypeTree = retTypeKind.isPrimitive()
930                         ? maker.Identifier(retType.toString())
931                         : maker.QualIdent(
932                                 workingCopy.getTypes().asElement(retType));
933
934                 VariableTree expectedValue = maker.Variable(
935                         maker.Modifiers(NO_MODIFIERS),
936                         EXP_RESULT_VAR_NAME,
937                         retTypeTree,
938                         getDefaultValue(maker, retType));
939                 VariableTree actualValue = maker.Variable(
940                         maker.Modifiers(NO_MODIFIERS),
941                         RESULT_VAR_NAME,
942                         retTypeTree,
943                         methodCall);
944
945                 List JavaDoc<ExpressionTree> comparisonArgs = new ArrayList JavaDoc<ExpressionTree>(2);
946                 comparisonArgs.add(maker.Identifier(expectedValue.getName().toString()));
947                 comparisonArgs.add(maker.Identifier(actualValue.getName().toString()));
948
949                 MethodInvocationTree comparison = maker.MethodInvocation(
950                         Collections.<ExpressionTree>emptyList(), //type args.
951
maker.Identifier("assertEquals"), //NOI18N
952
comparisonArgs);
953                 StatementTree comparisonStmt = maker.ExpressionStatement(
954                         comparison);
955
956                 statements.add(expectedValue);
957                 statements.add(actualValue);
958                 statements.add(comparisonStmt);
959             }
960         }
961
962         //PENDING - source code hints
963
// if (generateSourceCodeHints) {
964
// // generate comments to bodies
965
// if (needsEmptyLine) {
966
// newBody.append('\n');
967
// needsEmptyLine = false;
968
// }
969
// newBody.append(NbBundle.getMessage(
970
// TestCreator.class,
971
// generateDefMethodBody
972
// ? "TestCreator.variantMethods.defaultComment"//NOI18N
973
// : "TestCreator.variantMethods.onlyComment")) //NOI18N
974
// .append('\n');
975
// }
976

977         if (setup.isGenerateDefMethodBody()) {
978             String JavaDoc failMsg = NbBundle.getMessage(
979                     TestCreator.class,
980                     "TestCreator.variantMethods.defaultFailMsg"); //NOI18N
981
MethodInvocationTree failMethodCall = maker.MethodInvocation(
982                     Collections.<ExpressionTree>emptyList(), //type args.
983
maker.Identifier("fail"), //NOI18N
984
Collections.<ExpressionTree>singletonList(
985                             maker.Literal(failMsg)));
986             statements.add(maker.ExpressionStatement(failMethodCall));
987         }
988
989         return maker.Block(statements, false);
990     }
991
992     /**
993      */

994     private StatementTree generateSystemOutPrintln(TreeMaker maker,
995                                                    String JavaDoc arg) {
996         MethodInvocationTree methodInvocation = maker.MethodInvocation(
997                 Collections.<ExpressionTree>emptyList(), //type args
998
maker.MemberSelect(
999                         maker.MemberSelect(
1000                                maker.Identifier("System"), "out"), "println"),//NOI18N
1001
Collections.<LiteralTree>singletonList(
1002                        maker.Literal(arg))); //args.
1003
return maker.ExpressionStatement(methodInvocation);
1004    }
1005
1006    /**
1007     */

1008    private List JavaDoc<VariableTree> generateParamVariables(
1009                                            TreeMaker maker,
1010                                            ExecutableElement srcMethod) {
1011        List JavaDoc<? extends VariableElement> params = srcMethod.getParameters();
1012        if ((params == null) || params.isEmpty()) {
1013            return Collections.<VariableTree>emptyList();
1014        }
1015
1016        Set JavaDoc<Modifier> noModifiers = Collections.<Modifier>emptySet();
1017        List JavaDoc<VariableTree> paramVariables = new ArrayList JavaDoc<VariableTree>(params.size());
1018        String JavaDoc[] varNames = getTestSkeletonVarNames(params);
1019        int index = 0;
1020        for (VariableElement param : params) {
1021            TypeMirror paramType = param.asType();
1022            paramVariables.add(
1023                    maker.Variable(maker.Modifiers(noModifiers),
1024                                   varNames[index++],
1025                                   maker.Type(paramType),
1026                                   getDefaultValue(maker, paramType)));
1027        }
1028        return paramVariables;
1029    }
1030
1031    /**
1032     */

1033    private List JavaDoc<IdentifierTree> createIdentifiers(
1034                                            TreeMaker maker,
1035                                            List JavaDoc<VariableTree> variables) {
1036        List JavaDoc<IdentifierTree> identifiers;
1037        if (variables.isEmpty()) {
1038            identifiers = Collections.<IdentifierTree>emptyList();
1039        } else {
1040            identifiers = new ArrayList JavaDoc<IdentifierTree>(variables.size());
1041            for (VariableTree var : variables) {
1042                identifiers.add(maker.Identifier(var.getName().toString()));
1043            }
1044        }
1045        return identifiers;
1046    }
1047
1048    /**
1049     * Builds list of variable names for use in a test method skeleton.
1050     * By default, names of variables are same as names of tested method's
1051     * declared parameters. There are three variable names reserved
1052     * for variables holding the instance the tested method will be called on,
1053     * the expected result and the actual result returned
1054     * by the tested method. This method resolves a potential conflict
1055     * if some of the tested method's parameter's name is one of these
1056     * reserved names - in this case, the variable name used is a slight
1057     * modification of the declared parameter's name. The method also resolves
1058     * cases that some or all parameters are without name - in this case,
1059     * an arbitrary name is assigned to each of these unnamed parameters.
1060     * The goal is to ensure that all of the used variable names are unique.
1061     *
1062     * @param sourceMethodParams
1063     * list of tested method's parameters (items are of type
1064     * <code>org.netbeans.jmi.javamodel.TypeParameter</code>)
1065     * @return variable names used for default values of the tested method's
1066     * parameters (the reserved variable names are not included)
1067     */

1068    private String JavaDoc[] getTestSkeletonVarNames(
1069            final List JavaDoc<? extends VariableElement> sourceMethodParams) {
1070
1071        /* Handle the trivial case: */
1072        if (sourceMethodParams.isEmpty()) {
1073            return new String JavaDoc[0];
1074        }
1075
1076        final int count = sourceMethodParams.size();
1077        String JavaDoc[] varNames = new String JavaDoc[count];
1078        boolean[] conflicts = new boolean[count];
1079        boolean issueFound = false;
1080
1081        Set JavaDoc<String JavaDoc> varNamesSet = new HashSet JavaDoc<String JavaDoc>((int) ((count + 2) * 1.4));
1082        varNamesSet.add(INSTANCE_VAR_NAME);
1083        varNamesSet.add(RESULT_VAR_NAME);
1084        varNamesSet.add(EXP_RESULT_VAR_NAME);
1085
1086        Iterator JavaDoc<? extends VariableElement> it = sourceMethodParams.iterator();
1087        for (int i = 0; i < count; i++) {
1088            String JavaDoc paramName = it.next().getSimpleName().toString();
1089            varNames[i] = paramName;
1090
1091            if (paramName == null) {
1092                issueFound = true;
1093            } else if (!varNamesSet.add(paramName)) {
1094                conflicts[i] = true;
1095                issueFound = true;
1096            } else {
1097                conflicts[i] = false;
1098            }
1099        }
1100
1101        if (issueFound) {
1102            for (int i = 0; i < count; i++) {
1103                String JavaDoc paramName;
1104                if (varNames[i] == null) {
1105                    paramName = ARTIFICAL_VAR_NAME_BASE + i;
1106                    if (varNamesSet.add(paramName)) {
1107                        varNames[i] = paramName;
1108                        continue;
1109                    } else {
1110                        conflicts[i] = true;
1111                    }
1112                }
1113                if (conflicts[i]) {
1114                    String JavaDoc paramNamePrefix = varNames[i] + '_';
1115
1116                    int index = 2;
1117                    while (!varNamesSet.add(
1118                                    paramName = (paramNamePrefix + (index++))));
1119                    varNames[i] = paramName;
1120                }
1121            }
1122        }
1123
1124        return varNames;
1125    }
1126
1127    /**
1128     */

1129    private ExpressionTree getDefaultValue(TreeMaker maker,
1130                                           TypeMirror type) {
1131        ExpressionTree defValue;
1132        TypeKind typeKind = type.getKind();
1133        if (typeKind.isPrimitive()) {
1134            switch (typeKind) {
1135                case BOOLEAN:
1136                    defValue = maker.Literal(Boolean.FALSE);
1137                    break;
1138                case CHAR:
1139                    defValue = maker.Literal(new Character JavaDoc(' '));
1140                    break;
1141                case BYTE:
1142                    defValue = maker.Literal(new Byte JavaDoc((byte) 0));
1143                    break;
1144                case SHORT:
1145                    defValue = maker.Literal(new Short JavaDoc((short) 0));
1146                    break;
1147                case INT:
1148                    defValue = maker.Literal(new Integer JavaDoc(0));
1149                    break;
1150                case FLOAT:
1151                    defValue = maker.Literal(new Float JavaDoc(0.0F));
1152                    break;
1153                case LONG:
1154                    defValue = maker.Literal(new Long JavaDoc(0L));
1155                    break;
1156                case DOUBLE:
1157                    defValue = maker.Literal(new Double JavaDoc(0.0));
1158                    break;
1159                default:
1160                    assert false : "unknown primitive type"; //NOI18N
1161
defValue = maker.Literal(new Integer JavaDoc(0));
1162                    break;
1163            }
1164        } else if ((typeKind == TypeKind.DECLARED)
1165                   && type.toString().equals("java.lang.String")) { //NOI18N
1166
defValue = maker.Literal(""); //NOI18N
1167
} else {
1168            defValue = maker.Literal(null);
1169        }
1170        return defValue;
1171    }
1172
1173    /**
1174     */

1175    private ExpressionTree generateNoArgConstructorCall(TreeMaker maker,
1176                                                        TypeElement cls) {
1177        return maker.NewClass(
1178                null, //enclosing instance
1179
Collections.<ExpressionTree>emptyList(),//type arguments
1180
maker.QualIdent(cls), //class identifier
1181
Collections.<ExpressionTree>emptyList(),//arguments list
1182
null); //class body
1183
}
1184
1185    /**
1186     */

1187    private List JavaDoc<ExecutableElement> findTestableMethods(TypeElement classElem) {
1188        List JavaDoc<ExecutableElement> methods
1189                = ElementFilter.methodsIn(classElem.getEnclosedElements());
1190
1191        if (methods.isEmpty()) {
1192            return Collections.<ExecutableElement>emptyList();
1193        }
1194
1195        List JavaDoc<ExecutableElement> testableMethods = null;
1196
1197        int skippedCount = 0;
1198        for (ExecutableElement method : methods) {
1199            if (isTestableMethod(method)) {
1200                if (testableMethods == null) {
1201                    testableMethods = new ArrayList JavaDoc<ExecutableElement>(
1202                                             methods.size() - skippedCount);
1203                }
1204                testableMethods.add(method);
1205            } else {
1206                skippedCount++;
1207            }
1208        }
1209
1210        return (testableMethods != null)
1211               ? testableMethods
1212               : Collections.<ExecutableElement>emptyList();
1213    }
1214
1215    /**
1216     */

1217    private boolean isTestableMethod(ExecutableElement method) {
1218        if (method.getKind() != ElementKind.METHOD) {
1219            throw new IllegalArgumentException JavaDoc();
1220        }
1221
1222        return setup.isMethodTestable(method);
1223    }
1224
1225    /**
1226     */

1227    protected boolean hasAccessibleNoArgConstructor(TypeElement srcClass) {
1228        boolean answer;
1229
1230        List JavaDoc<ExecutableElement> constructors
1231             = ElementFilter.constructorsIn(srcClass.getEnclosedElements());
1232
1233        if (constructors.isEmpty()) {
1234            answer = true; //no explicit constructor -> synthetic no-arg. constructor
1235
} else {
1236            answer = false;
1237            for (ExecutableElement constructor : constructors) {
1238                if (constructor.getParameters().isEmpty()) {
1239                    answer = !constructor.getModifiers().contains(Modifier.PRIVATE);
1240                    break;
1241                }
1242            }
1243        }
1244        return answer;
1245    }
1246
1247    /**
1248     */

1249    private boolean throwsNonRuntimeExceptions(CompilationInfo compInfo,
1250                                               ExecutableElement method) {
1251        List JavaDoc<? extends TypeMirror> thrownTypes = method.getThrownTypes();
1252        if (thrownTypes.isEmpty()) {
1253            return false;
1254        }
1255
1256        String JavaDoc runtimeExcName = "java.lang.RuntimeException"; //NOI18N
1257
TypeElement runtimeExcElement = compInfo.getElements()
1258                                        .getTypeElement(runtimeExcName);
1259        if (runtimeExcElement == null) {
1260            Logger.getLogger("junit").log( //NOI18N
1261
Level.WARNING,
1262                    "Could not find TypeElement for " //NOI18N
1263
+ runtimeExcName);
1264            return true;
1265        }
1266
1267        Types types = compInfo.getTypes();
1268        TypeMirror runtimeExcType = runtimeExcElement.asType();
1269        for (TypeMirror exceptionType : thrownTypes) {
1270            if (!types.isSubtype(exceptionType, runtimeExcType)) {
1271                return true;
1272            }
1273        }
1274
1275        return false;
1276    }
1277
1278    /**
1279     */

1280    private <T extends Element> List JavaDoc<T> resolveHandles(
1281                                            CompilationInfo compInfo,
1282                                            List JavaDoc<ElementHandle<T>> handles) {
1283        if (handles == null) {
1284            return null;
1285        }
1286        if (handles.isEmpty()) {
1287            return Collections.<T>emptyList();
1288        }
1289
1290        List JavaDoc<T> elements = new ArrayList JavaDoc<T>(handles.size());
1291        for (ElementHandle<T> handle : handles) {
1292            elements.add(handle.resolve(compInfo));
1293        }
1294        return elements;
1295    }
1296
1297    /**
1298     * Stops this creator - cancels creation of a test class.
1299     */

1300    public void cancel() {
1301        cancelled = true;
1302    }
1303
1304    /**
1305     */

1306    private void classProcessed(ClassTree cls) {
1307        if (processedClassNames == null) {
1308            processedClassNames = new ArrayList JavaDoc<String JavaDoc>(4);
1309        }
1310        processedClassNames.add(cls.getSimpleName().toString());
1311    }
1312
1313    /**
1314     */

1315    List JavaDoc<String JavaDoc> getProcessedClassNames() {
1316        return processedClassNames != null
1317               ? processedClassNames
1318               : Collections.<String JavaDoc>emptyList();
1319    }
1320
1321    /* private methods */
1322    
1323//XXX: retouche
1324
// /**
1325
// *
1326
// * @param cls JavaClass to generate the comment to.
1327
// */
1328
// private static void addClassBodyComment(JavaClass cls) {
1329
// int off = cls.getEndOffset() - 1;
1330
// String theComment1 = NbBundle.getMessage(TestCreator.class,
1331
// CLASS_COMMENT_LINE1);
1332
// String theComment2 = NbBundle.getMessage(TestCreator.class,
1333
// CLASS_COMMENT_LINE2);
1334
// String indent = getIndentString();
1335
// DiffElement diff = new DiffElement(
1336
// off,
1337
// off,
1338
// indent + theComment1 + '\n'
1339
// + indent + theComment2 + '\n' + '\n');
1340
// ((ResourceImpl) cls.getResource()).addExtDiff(diff);
1341
// }
1342

1343    /**
1344     */

1345    private String JavaDoc getInitialMainMethodBody() {
1346        if (initialMainMethodBody == null) {
1347            initialMainMethodBody = JUnitSettings.getDefault()
1348                                    .getGenerateMainMethodBody();
1349            if (initialMainMethodBody == null) {
1350                /*
1351                 * set it to a non-null value so that this method does not try
1352                 * to load it from the settings next time
1353                 */

1354                initialMainMethodBody = ""; //NOI18N
1355
}
1356        }
1357        return initialMainMethodBody;
1358    }
1359    
1360    /**
1361     * Creates a {@code Set} of {@code Modifier}s from the given list
1362     * of modifiers.
1363     *
1364     * @param modifiers modifiers that should be contained in the set
1365     * @return set containing exactly the given modifiers
1366     */

1367    static Set JavaDoc<Modifier> createModifierSet(Modifier... modifiers) {
1368        EnumSet JavaDoc<Modifier> modifierSet = EnumSet.noneOf(Modifier.class);
1369        for (Modifier m : modifiers) {
1370            modifierSet.add(m);
1371        }
1372        return modifierSet;
1373    }
1374    
1375}
1376
Popular Tags