KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > junit > wizards > NewTestCaseCreationWizardPage


1 /*******************************************************************************
2  * Copyright (c) 2000, 2004 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Common Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  * Sebastian Davids - bug 38507
11  *******************************************************************************/

12 package org.eclipse.jdt.internal.junit.wizards;
13
14 import java.lang.reflect.InvocationTargetException JavaDoc;
15 import java.util.ArrayList JavaDoc;
16 import java.util.Arrays JavaDoc;
17 import java.util.List JavaDoc;
18 import java.util.ListIterator JavaDoc;
19
20 import org.eclipse.core.runtime.CoreException;
21 import org.eclipse.core.runtime.IPath;
22 import org.eclipse.core.runtime.IProgressMonitor;
23 import org.eclipse.core.runtime.IStatus;
24 import org.eclipse.core.runtime.Path;
25
26 import org.eclipse.core.resources.IProject;
27 import org.eclipse.core.resources.ResourcesPlugin;
28
29 import org.eclipse.jdt.core.Flags;
30 import org.eclipse.jdt.core.IClassFile;
31 import org.eclipse.jdt.core.IClasspathEntry;
32 import org.eclipse.jdt.core.ICompilationUnit;
33 import org.eclipse.jdt.core.IJavaElement;
34 import org.eclipse.jdt.core.IJavaProject;
35 import org.eclipse.jdt.core.IMethod;
36 import org.eclipse.jdt.core.IPackageFragment;
37 import org.eclipse.jdt.core.IPackageFragmentRoot;
38 import org.eclipse.jdt.core.IType;
39 import org.eclipse.jdt.core.ITypeHierarchy;
40 import org.eclipse.jdt.core.JavaConventions;
41 import org.eclipse.jdt.core.JavaCore;
42 import org.eclipse.jdt.core.JavaModelException;
43 import org.eclipse.jdt.core.Signature;
44 import org.eclipse.jdt.core.search.IJavaSearchScope;
45 import org.eclipse.jdt.core.search.SearchEngine;
46 import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
47 import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
48 import org.eclipse.jdt.internal.junit.ui.IJUnitHelpContextIds;
49 import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
50 import org.eclipse.jdt.internal.junit.util.JUnitStatus;
51 import org.eclipse.jdt.internal.junit.util.JUnitStubUtility;
52 import org.eclipse.jdt.internal.junit.util.LayoutUtil;
53 import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
54 import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings;
55 import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
56 import org.eclipse.jdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
57 import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
58 import org.eclipse.jdt.internal.ui.util.SWTUtil;
59 import org.eclipse.jdt.ui.IJavaElementSearchConstants;
60 import org.eclipse.jdt.ui.JavaUI;
61 import org.eclipse.jdt.ui.wizards.NewTypeWizardPage;
62 import org.eclipse.jface.dialogs.Dialog;
63 import org.eclipse.jface.dialogs.ErrorDialog;
64 import org.eclipse.jface.dialogs.IDialogSettings;
65 import org.eclipse.jface.dialogs.MessageDialog;
66 import org.eclipse.jface.operation.IRunnableWithProgress;
67 import org.eclipse.jface.viewers.IStructuredSelection;
68 import org.eclipse.jface.window.Window;
69 import org.eclipse.swt.SWT;
70 import org.eclipse.swt.events.ModifyEvent;
71 import org.eclipse.swt.events.ModifyListener;
72 import org.eclipse.swt.events.SelectionEvent;
73 import org.eclipse.swt.events.SelectionListener;
74 import org.eclipse.swt.layout.GridData;
75 import org.eclipse.swt.layout.GridLayout;
76 import org.eclipse.swt.widgets.Button;
77 import org.eclipse.swt.widgets.Composite;
78 import org.eclipse.swt.widgets.Label;
79 import org.eclipse.swt.widgets.Shell;
80 import org.eclipse.swt.widgets.Text;
81 import org.eclipse.ui.PlatformUI;
82 import org.eclipse.ui.dialogs.SelectionDialog;
83 import org.eclipse.ui.help.WorkbenchHelp;
84
85 /**
86  * The first page of the TestCase creation wizard.
87  */

88 public class NewTestCaseCreationWizardPage extends NewTypeWizardPage implements IAboutToRunOperation {
89
90     private final static String JavaDoc PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$
91
private final static String JavaDoc CLASS_TO_TEST= PAGE_NAME + ".classtotest"; //$NON-NLS-1$
92
private final static String JavaDoc TEST_SUFFIX= "Test"; //$NON-NLS-1$
93
private final static String JavaDoc SETUP= "setUp"; //$NON-NLS-1$
94
private final static String JavaDoc TEARDOWN= "tearDown"; //$NON-NLS-1$
95

96     private final static String JavaDoc STORE_GENERATE_MAIN= PAGE_NAME + ".GENERATE_MAIN"; //$NON-NLS-1$
97
private final static String JavaDoc STORE_USE_TESTRUNNER= PAGE_NAME + ".USE_TESTRUNNER"; //$NON-NLS-1$
98
private final static String JavaDoc STORE_TESTRUNNER_TYPE= PAGE_NAME + ".TESTRUNNER_TYPE"; //$NON-NLS-1$
99

100     private String JavaDoc fDefaultClassToTest;
101     private NewTestCaseCreationWizardPage2 fPage2;
102     private MethodStubsSelectionButtonGroup fMethodStubsButtons;
103
104     private IType fClassToTest;
105     private IStatus fClassToTestStatus;
106     private IStatus fTestClassStatus;
107
108     private int fIndexOfFirstTestMethod;
109
110     private Label fClassToTestLabel;
111     private Text fClassToTestText;
112     private Button fClassToTestButton;
113     private JavaTypeCompletionProcessor fClassToTestCompletionProcessor;
114     
115     private boolean fFirstTime;
116     private String JavaDoc fMainMethod;
117
118     public NewTestCaseCreationWizardPage() {
119         super(true, PAGE_NAME);
120         fFirstTime= true;
121         
122         setTitle(WizardMessages.getString("NewTestClassWizPage.title")); //$NON-NLS-1$
123
setDescription(WizardMessages.getString("NewTestClassWizPage.description")); //$NON-NLS-1$
124

125         String JavaDoc[] buttonNames= new String JavaDoc[] {
126             "public static void main(Strin&g[] args)", //$NON-NLS-1$
127
/* Add testrunner statement to main Method */
128             WizardMessages.getString("NewTestClassWizPage.methodStub.testRunner"), //$NON-NLS-1$
129
WizardMessages.getString("NewTestClassWizPage.methodStub.setUp"), //$NON-NLS-1$
130
WizardMessages.getString("NewTestClassWizPage.methodStub.tearDown"), //$NON-NLS-1$
131
WizardMessages.getString("NewTestClassWizPage.methodStub.constructor") //$NON-NLS-1$
132
};
133         
134         fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 1);
135         fMethodStubsButtons.setLabelText(WizardMessages.getString("NewTestClassWizPage.method.Stub.label")); //$NON-NLS-1$
136

137         fClassToTestCompletionProcessor= new JavaTypeCompletionProcessor(false, false); //$NON-NLS-1$
138

139         fClassToTestStatus= new JUnitStatus();
140         fTestClassStatus= new JUnitStatus();
141         
142         fDefaultClassToTest= ""; //$NON-NLS-1$
143
}
144
145     /**
146      * Should be called from the wizard with the initial selection and the 2nd page of the wizard..
147      */

148     public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) {
149         fPage2= page2;
150         IJavaElement element= getInitialJavaElement(selection);
151
152         initContainerPage(element);
153         initTypePage(element);
154         doStatusUpdate();
155         // put default class to test
156
if (element != null) {
157             IType classToTest= null;
158             // evaluate the enclosing type
159
IType typeInCompUnit= (IType) element.getAncestor(IJavaElement.TYPE);
160             if (typeInCompUnit != null) {
161                 if (typeInCompUnit.getCompilationUnit() != null) {
162                     classToTest= typeInCompUnit;
163                 }
164             } else {
165                 ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
166                 if (cu != null)
167                     classToTest= cu.findPrimaryType();
168                 else {
169                     if (element instanceof IClassFile) {
170                         try {
171                             IClassFile cf= (IClassFile) element;
172                             if (cf.isStructureKnown())
173                                 classToTest= cf.getType();
174                         } catch(JavaModelException e) {
175                             JUnitPlugin.log(e);
176                         }
177                     }
178                 }
179             }
180             if (classToTest != null) {
181                 try {
182                     if (!TestSearchEngine.isTestImplementor(classToTest)) {
183                         fDefaultClassToTest= classToTest.getFullyQualifiedName();
184                     }
185                 } catch (JavaModelException e) {
186                     JUnitPlugin.log(e);
187                 }
188             }
189         }
190         fMethodStubsButtons.setSelection(0, false); //main
191
fMethodStubsButtons.setSelection(1, false); //add textrunner
192
fMethodStubsButtons.setEnabled(1, false); //add text
193
fMethodStubsButtons.setSelection(2, false); //setUp
194
fMethodStubsButtons.setSelection(3, false); //tearDown
195
fMethodStubsButtons.setSelection(4, false); //constructor
196
}
197     
198     /**
199      * @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
200      */

201     protected void handleFieldChanged(String JavaDoc fieldName) {
202         super.handleFieldChanged(fieldName);
203         if (fieldName.equals(CLASS_TO_TEST)) {
204             fClassToTestStatus= classToTestClassChanged();
205         } else if (fieldName.equals(SUPER)) {
206             validateSuperClass();
207             if (!fFirstTime)
208                 fTestClassStatus= typeNameChanged();
209         } else if (fieldName.equals(TYPENAME)) {
210             fTestClassStatus= typeNameChanged();
211         } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER) || fieldName.equals(SUPER)) {
212             if (fieldName.equals(PACKAGE))
213                 fPackageStatus= packageChanged();
214             if (!fFirstTime) {
215                 validateSuperClass();
216                 fClassToTestStatus= classToTestClassChanged();
217                 fTestClassStatus= typeNameChanged();
218             }
219             if (fieldName.equals(CONTAINER)) {
220                 validateJUnitOnBuildPath();
221             }
222         }
223         doStatusUpdate();
224     }
225
226     // ------ validation --------
227
private void doStatusUpdate() {
228         // status of all used components
229
IStatus[] status= new IStatus[] {
230             fContainerStatus,
231             fPackageStatus,
232             fTestClassStatus,
233             fClassToTestStatus,
234             fModifierStatus,
235             fSuperClassStatus
236         };
237         
238         // the mode severe status will be displayed and the ok button enabled/disabled.
239
updateStatus(status);
240     }
241
242     /*
243      * @see IDialogPage#createControl(Composite)
244      */

245     public void createControl(Composite parent) {
246         initializeDialogUnits(parent);
247         
248         Composite composite= new Composite(parent, SWT.NONE);
249         
250         int nColumns= 4;
251         
252         GridLayout layout= new GridLayout();
253         layout.numColumns= nColumns;
254         composite.setLayout(layout);
255
256         createContainerControls(composite, nColumns);
257         createPackageControls(composite, nColumns);
258         createSeparator(composite, nColumns);
259         createTypeNameControls(composite, nColumns);
260         createSuperClassControls(composite, nColumns);
261         createMethodStubSelectionControls(composite, nColumns);
262         setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true);
263         createSeparator(composite, nColumns);
264         createClassToTestControls(composite, nColumns);
265         
266         setControl(composite);
267             
268         //set default and focus
269
if (fDefaultClassToTest.length() > 0) {
270             fClassToTestText.setText(fDefaultClassToTest);
271             setTypeName(Signature.getSimpleName(fDefaultClassToTest)+TEST_SUFFIX, true);
272         }
273         restoreWidgetValues();
274         Dialog.applyDialogFont(composite);
275         WorkbenchHelp.setHelp(composite, IJUnitHelpContextIds.NEW_TESTCASE_WIZARD_PAGE);
276
277     }
278
279     private void createMethodStubSelectionControls(Composite composite, int nColumns) {
280         LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns);
281         LayoutUtil.createEmptySpace(composite,1);
282         LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1);
283     }
284
285     private void createClassToTestControls(Composite composite, int nColumns) {
286         fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP);
287         fClassToTestLabel.setFont(composite.getFont());
288
289         fClassToTestLabel.setText(WizardMessages.getString("NewTestClassWizPage.class_to_test.label")); //$NON-NLS-1$
290
GridData gd= new GridData();
291         gd.horizontalSpan= 1;
292         fClassToTestLabel.setLayoutData(gd);
293
294         fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER);
295         fClassToTestText.setEnabled(true);
296         fClassToTestText.setFont(composite.getFont());
297         fClassToTestText.addModifyListener(new ModifyListener() {
298             public void modifyText(ModifyEvent e) {
299                 handleFieldChanged(CLASS_TO_TEST);
300             }
301         });
302         gd= new GridData();
303         gd.horizontalAlignment= GridData.FILL;
304         gd.grabExcessHorizontalSpace= true;
305         gd.horizontalSpan= nColumns - 2;
306         fClassToTestText.setLayoutData(gd);
307         
308         fClassToTestButton= new Button(composite, SWT.PUSH);
309         fClassToTestButton.setText(WizardMessages.getString("NewTestClassWizPage.class_to_test.browse")); //$NON-NLS-1$
310
fClassToTestButton.setEnabled(true);
311         fClassToTestButton.addSelectionListener(new SelectionListener() {
312             public void widgetDefaultSelected(SelectionEvent e) {
313                 classToTestButtonPressed();
314             }
315             public void widgetSelected(SelectionEvent e) {
316                 classToTestButtonPressed();
317             }
318         });
319         gd= new GridData();
320         gd.horizontalAlignment= GridData.FILL;
321         gd.grabExcessHorizontalSpace= false;
322         gd.horizontalSpan= 1;
323         gd.heightHint = SWTUtil.getButtonHeightHint(fClassToTestButton);
324         gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton);
325         fClassToTestButton.setLayoutData(gd);
326
327         ControlContentAssistHelper.createTextContentAssistant(fClassToTestText, fClassToTestCompletionProcessor);
328     }
329
330     private void classToTestButtonPressed() {
331         IType type= chooseClassToTestType();
332         if (type != null) {
333             fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type));
334             handleFieldChanged(CLASS_TO_TEST);
335         }
336     }
337
338     private IType chooseClassToTestType() {
339         IPackageFragmentRoot root= getPackageFragmentRoot();
340         if (root == null)
341             return null;
342
343         IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
344         IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
345         
346         IType type= null;
347         try {
348             SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, getClassToTestText());
349             dialog.setTitle(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.title")); //$NON-NLS-1$
350
dialog.setMessage(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.message")); //$NON-NLS-1$
351
dialog.open();
352             if (dialog.getReturnCode() != Window.OK)
353                 return type;
354             else {
355                 Object JavaDoc[] resultArray= dialog.getResult();
356                 if (resultArray != null && resultArray.length > 0)
357                     type= (IType) resultArray[0];
358             }
359         } catch (JavaModelException e) {
360             JUnitPlugin.log(e);
361         }
362         return type;
363     }
364
365     /*
366      * @see org.eclipse.jdt.ui.wizards.NewTypeWizardPage#packageChanged()
367      */

368     protected IStatus packageChanged() {
369         IStatus status= super.packageChanged();
370         fClassToTestCompletionProcessor.setPackageFragment(getPackageFragment());
371         return status;
372     }
373     
374     private IStatus classToTestClassChanged() {
375         fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); // sets the test class field?
376
IStatus status= validateClassToTest();
377         return status;
378     }
379
380     /**
381      * Returns the content of the class to test text field.
382      */

383     public String JavaDoc getClassToTestText() {
384         return fClassToTestText.getText();
385     }
386     
387     /**
388      * Returns the class to be tested.
389      */

390     public IType getClassToTest() {
391         return fClassToTest;
392     }
393
394     /**
395      * Sets the name of the class to test.
396      */

397     public void setClassToTest(String JavaDoc name) {
398         fClassToTestText.setText(name);
399     }
400
401     /**
402      * @see NewTypeWizardPage#createTypeMembers(IType, ImportsManager, IProgressMonitor)
403      */

404     protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
405         fIndexOfFirstTestMethod= 0;
406
407         if (fMethodStubsButtons.isSelected(0))
408             createMain(type);
409         
410         if (fMethodStubsButtons.isSelected(2)) {
411             createSetUp(type, imports);
412         }
413         
414         if (fMethodStubsButtons.isSelected(3)) {
415             createTearDown(type, imports);
416         }
417
418         if (fMethodStubsButtons.isSelected(4))
419             createConstructor(type, imports);
420
421         if (fClassToTest != null) {
422             createTestMethodStubs(type);
423         }
424     }
425
426     private void createConstructor(IType type, ImportsManager imports) throws JavaModelException {
427         ITypeHierarchy typeHierarchy= null;
428         IType[] superTypes= null;
429         String JavaDoc constr= ""; //$NON-NLS-1$
430
IMethod methodTemplate= null;
431         if (type.exists()) {
432             typeHierarchy= type.newSupertypeHierarchy(null);
433             superTypes= typeHierarchy.getAllSuperclasses(type);
434             for (int i= 0; i < superTypes.length; i++) {
435                 if (superTypes[i].exists()) {
436                     IMethod constrMethod= superTypes[i].getMethod(superTypes[i].getElementName(), new String JavaDoc[] {"Ljava.lang.String;"}); //$NON-NLS-1$
437
if (constrMethod.exists() && constrMethod.isConstructor()) {
438                         methodTemplate= constrMethod;
439                         break;
440                     }
441                 }
442             }
443         }
444         CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
445         if (methodTemplate != null) {
446             GenStubSettings genStubSettings= new GenStubSettings(settings);
447             genStubSettings.fCallSuper= true;
448             genStubSettings.fMethodOverwrites= true;
449             constr= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports);
450         } else {
451             constr += "public "+getTypeName()+"(String name) {" + //$NON-NLS-1$ //$NON-NLS-2$
452
getLineDelimiter() +
453                     "super(name);" + //$NON-NLS-1$
454
getLineDelimiter() +
455                     "}" + //$NON-NLS-1$
456
getLineDelimiter() + getLineDelimiter();
457         }
458         type.createMethod(constr, null, true, null);
459         fIndexOfFirstTestMethod++;
460     }
461
462     private void createMain(IType type) throws JavaModelException {
463         type.createMethod(fMainMethod, null, false, null);
464         fIndexOfFirstTestMethod++;
465     }
466
467     private void createSetUp(IType type, ImportsManager imports) throws JavaModelException {
468         ITypeHierarchy typeHierarchy= null;
469         IType[] superTypes= null;
470         String JavaDoc setUp= ""; //$NON-NLS-1$
471
IMethod methodTemplate= null;
472         if (type.exists()) {
473             typeHierarchy= type.newSupertypeHierarchy(null);
474             superTypes= typeHierarchy.getAllSuperclasses(type);
475             for (int i= 0; i < superTypes.length; i++) {
476                 if (superTypes[i].exists()) {
477                     IMethod testMethod= superTypes[i].getMethod(SETUP, new String JavaDoc[] {});
478                     if (testMethod.exists()) {
479                         methodTemplate= testMethod;
480                         break;
481                     }
482                 }
483             }
484         }
485         CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
486         if (methodTemplate != null) {
487             GenStubSettings genStubSettings= new GenStubSettings(settings);
488             genStubSettings.fCallSuper= true;
489             genStubSettings.fMethodOverwrites= true;
490             setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports);
491         } else {
492             if (settings.createComments)
493                 setUp= "/**" + //$NON-NLS-1$
494
getLineDelimiter() +
495                     " * Sets up the fixture, for example, open a network connection." + //$NON-NLS-1$
496
getLineDelimiter() +
497                     " * This method is called before a test is executed." + //$NON-NLS-1$
498
getLineDelimiter() +
499                     " * @throws Exception" + //$NON-NLS-1$
500
getLineDelimiter() +
501                     " */" + //$NON-NLS-1$
502
getLineDelimiter();
503             setUp+= "protected void "+SETUP+"() throws Exception {}" + //$NON-NLS-1$ //$NON-NLS-2$
504
getLineDelimiter() + getLineDelimiter();
505         }
506         type.createMethod(setUp, null, false, null);
507         fIndexOfFirstTestMethod++;
508     }
509     
510     private void createTearDown(IType type, ImportsManager imports) throws JavaModelException {
511         ITypeHierarchy typeHierarchy= null;
512         IType[] superTypes= null;
513         String JavaDoc tearDown= ""; //$NON-NLS-1$
514
IMethod methodTemplate= null;
515         if (type.exists()) {
516             if (typeHierarchy == null) {
517                 typeHierarchy= type.newSupertypeHierarchy(null);
518                 superTypes= typeHierarchy.getAllSuperclasses(type);
519             }
520             for (int i= 0; i < superTypes.length; i++) {
521                 if (superTypes[i].exists()) {
522                     IMethod testM= superTypes[i].getMethod(TEARDOWN, new String JavaDoc[] {});
523                     if (testM.exists()) {
524                         methodTemplate= testM;
525                         break;
526                     }
527                 }
528             }
529         }
530         CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
531         if (methodTemplate != null) {
532             GenStubSettings genStubSettings= new GenStubSettings(settings);
533             genStubSettings.fCallSuper= true;
534             genStubSettings.fMethodOverwrites= true;
535             tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports);
536             type.createMethod(tearDown, null, false, null);
537             fIndexOfFirstTestMethod++;
538         }
539     }
540
541     private void createTestMethodStubs(IType type) throws JavaModelException {
542         IMethod[] methods= fPage2.getCheckedMethods();
543         if (methods.length == 0)
544             return;
545         /* find overloaded methods */
546         IMethod[] allMethodsArray= fPage2.getAllMethods();
547         List JavaDoc allMethods= new ArrayList JavaDoc();
548         allMethods.addAll(Arrays.asList(allMethodsArray));
549         List JavaDoc overloadedMethods= getOveloadedMethods(allMethods);
550             
551         /* used when for example both sum and Sum methods are present. Then
552          * sum -> testSum
553          * Sum -> testSum1
554          */

555         List JavaDoc newMethodsNames= new ArrayList JavaDoc();
556             for (int i = 0; i < methods.length; i++) {
557             IMethod testedMethod= methods[i];
558             String JavaDoc elementName= testedMethod.getElementName();
559             StringBuffer JavaDoc methodName= new StringBuffer JavaDoc(NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1));
560             StringBuffer JavaDoc newMethod= new StringBuffer JavaDoc();
561     
562             if (overloadedMethods.contains(testedMethod)) {
563                 appendMethodComment(newMethod, testedMethod);
564                 String JavaDoc[] params= testedMethod.getParameterTypes();
565                 appendParameterNamesToMethodName(methodName, params);
566             }
567             /* Should I for examples have methods
568              * void foo(java.lang.StringBuffer sb) {}
569              * void foo(mypackage1.StringBuffer sb) {}
570              * void foo(mypackage2.StringBuffer sb) {}
571              * I will get in the test class:
572              * testFooStringBuffer()
573              * testFooStringBuffer1()
574              * testFooStringBuffer2()
575              */

576             if (newMethodsNames.contains(methodName.toString())) {
577                 int suffix= 1;
578                 while (newMethodsNames.contains(methodName.toString() + Integer.toString(suffix)))
579                     suffix++;
580                 methodName.append(Integer.toString(suffix));
581             }
582             newMethodsNames.add(methodName.toString());
583             newMethod.append("public ");//$NON-NLS-1$
584
if (fPage2.getCreateFinalMethodStubsButtonSelection())
585                 newMethod.append("final "); //$NON-NLS-1$
586
newMethod.append("void ");//$NON-NLS-1$
587
newMethod.append(methodName.toString());
588             newMethod.append("()");//$NON-NLS-1$
589
appendTestMethodBody(newMethod, testedMethod);
590             type.createMethod(newMethod.toString(), null, false, null);
591         }
592     }
593     
594     private String JavaDoc getLineDelimiter(){
595         IType classToTest= getClassToTest();
596         
597         if (classToTest != null && classToTest.exists())
598             return JUnitStubUtility.getLineDelimiterUsed(classToTest);
599         else
600             return JUnitStubUtility.getLineDelimiterUsed(getPackageFragment());
601     }
602     
603     private void appendTestMethodBody(StringBuffer JavaDoc newMethod, IMethod testedMethod) {
604         newMethod.append("{"); //$NON-NLS-1$
605
if (createTasks()){
606             newMethod.append(getLineDelimiter());
607             newMethod.append("//"); //$NON-NLS-1$
608
newMethod.append(JUnitStubUtility.getTodoTaskTag(getPackageFragment().getJavaProject()));
609             newMethod.append(WizardMessages.getFormattedString("NewTestClassWizPage.marker.message", testedMethod.getElementName())); //$NON-NLS-1$
610
newMethod.append(getLineDelimiter());
611         }
612         newMethod.append("}").append(getLineDelimiter()).append(getLineDelimiter()); //$NON-NLS-1$
613
}
614
615     public void appendParameterNamesToMethodName(StringBuffer JavaDoc methodName, String JavaDoc[] params) {
616         for (int i= 0; i < params.length; i++) {
617             String JavaDoc param= params[i];
618             methodName.append(Signature.getSimpleName(Signature.toString(Signature.getElementType(param))));
619             for (int j= 0, arrayCount= Signature.getArrayCount(param); j < arrayCount; j++) {
620                 methodName.append("Array"); //$NON-NLS-1$
621
}
622         }
623     }
624
625     private void appendMethodComment(StringBuffer JavaDoc newMethod, IMethod method) throws JavaModelException {
626         String JavaDoc returnType= Signature.toString(method.getReturnType());
627         String JavaDoc body= WizardMessages.getFormattedString("NewTestClassWizPage.comment.class_to_test", new String JavaDoc[]{returnType, method.getElementName()}); //$NON-NLS-1$
628
newMethod.append("/*");//$NON-NLS-1$
629
newMethod.append(getLineDelimiter());
630         newMethod.append(" * ");//$NON-NLS-1$
631
newMethod.append(body);
632         newMethod.append("(");//$NON-NLS-1$
633
String JavaDoc[] paramTypes= method.getParameterTypes();
634         if (paramTypes.length > 0) {
635             if (paramTypes.length > 1) {
636                 for (int j= 0; j < paramTypes.length-1; j++) {
637                     newMethod.append(Signature.toString(paramTypes[j])+", "); //$NON-NLS-1$
638
}
639             }
640             newMethod.append(Signature.toString(paramTypes[paramTypes.length-1]));
641         }
642         newMethod.append(")");//$NON-NLS-1$
643
newMethod.append(getLineDelimiter());
644         newMethod.append(" */");//$NON-NLS-1$
645
newMethod.append(getLineDelimiter());
646     }
647
648     private List JavaDoc getOveloadedMethods(List JavaDoc allMethods) {
649         List JavaDoc overloadedMethods= new ArrayList JavaDoc();
650         for (int i= 0; i < allMethods.size(); i++) {
651             IMethod current= (IMethod) allMethods.get(i);
652             String JavaDoc currentName= current.getElementName();
653             boolean currentAdded= false;
654             for (ListIterator JavaDoc iter= allMethods.listIterator(i+1); iter.hasNext(); ) {
655                 IMethod iterMethod= (IMethod) iter.next();
656                 if (iterMethod.getElementName().equals(currentName)) {
657                     //method is overloaded
658
if (!currentAdded) {
659                         overloadedMethods.add(current);
660                         currentAdded= true;
661                     }
662                     overloadedMethods.add(iterMethod);
663                     iter.remove();
664                 }
665             }
666         }
667         return overloadedMethods;
668     }
669
670     /**
671      * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean)
672      */

673     public void setVisible(boolean visible) {
674         super.setVisible(visible);
675
676         if (visible && fFirstTime) {
677             if (getClassToTestText().equals("")) //$NON-NLS-1$
678
setPageComplete(false);
679             else
680                 handleFieldChanged(CLASS_TO_TEST); //creates error message when wizard is opened if TestCase already exists
681
fFirstTime= false;
682         }
683         
684         if (visible) setFocus();
685     }
686
687     private void validateJUnitOnBuildPath() {
688         IPackageFragmentRoot root= getPackageFragmentRoot();
689         if (root == null)
690             return;
691         IJavaProject jp= root.getJavaProject();
692         
693         try {
694             if (jp.findType(JUnitPlugin.TEST_SUPERCLASS_NAME) != null)
695                 return;
696         } catch (JavaModelException e) {
697         }
698         if (MessageDialog.openQuestion(getShell(), WizardMessages.getString("NewTestClassWizPage.not_on_buildpath.title"), WizardMessages.getString("NewTestClassWizPage.not_on_buildpath.message"))) { //$NON-NLS-1$ //$NON-NLS-2$
699
try {
700                 addJUnitToBuildPath(getShell(), jp);
701                 return;
702             } catch(JavaModelException e) {
703                 ErrorDialog.openError(getShell(), WizardMessages.getString("NewTestClassWizPage.cannot_add.title"), WizardMessages.getString("NewTestClassWizPage.cannot_add.message"), e.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
704
}
705         }
706         JUnitStatus status= new JUnitStatus();
707         status.setWarning(WizardMessages.getString("NewTestClassWizPage.error.junitNotOnbuildpath")); //$NON-NLS-1$
708
fContainerStatus= status;
709     }
710     
711     public static void addJUnitToBuildPath(Shell shell, IJavaProject project) throws JavaModelException {
712         IProject junitProject= ResourcesPlugin.getWorkspace().getRoot().getProject("org.junit"); //$NON-NLS-1$
713
IClasspathEntry entry;
714         if (junitProject.exists()) {
715             entry= JavaCore.newProjectEntry(junitProject.getFullPath());
716         } else {
717             IPath junitHome= new Path(JUnitPlugin.JUNIT_HOME);
718             IPath sourceHome= new Path("ECLIPSE_HOME"); //$NON-NLS-1$
719
entry= JavaCore.newVariableEntry(
720                 junitHome.append("junit.jar"), //$NON-NLS-1$
721
//TODO: find a better solution than declaring a classpath variable
722
sourceHome.append("plugins/org.eclipse.jdt.source_3.0.0/src/org.junit_3.8.1/junitsrc.zip"), //$NON-NLS-1$
723
null
724             );
725         }
726         addToClasspath(shell, project, entry);
727     }
728     
729     private static void addToClasspath(Shell shell, final IJavaProject project, IClasspathEntry entry) throws JavaModelException {
730         IClasspathEntry[] oldEntries= project.getRawClasspath();
731         for (int i= 0; i < oldEntries.length; i++) {
732             if (oldEntries[i].equals(entry)) {
733                 return;
734             }
735         }
736         int nEntries= oldEntries.length;
737         final IClasspathEntry[] newEntries= new IClasspathEntry[nEntries + 1];
738         System.arraycopy(oldEntries, 0, newEntries, 0, nEntries);
739         newEntries[nEntries]= entry;
740         // fix for 64974 OCE in New JUnit Test Case wizard while workspace is locked [JUnit]
741
try {
742             PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() {
743                 public void run(IProgressMonitor monitor) throws InvocationTargetException JavaDoc, InterruptedException JavaDoc {
744                     try {
745                         project.setRawClasspath(newEntries, monitor);
746                     } catch (JavaModelException e) {
747                         throw new InvocationTargetException JavaDoc(e);
748                     }
749                 }
750             });
751         } catch (InvocationTargetException JavaDoc e) {
752             Throwable JavaDoc t = e.getTargetException();
753             if (t instanceof CoreException) {
754                 ErrorDialog.openError(shell, WizardMessages.getString("NewTestClassWizPage.cannot_add.title"), WizardMessages.getString("NewTestClassWizPage.cannot_add.message"), ((CoreException)t).getStatus()); //$NON-NLS-1$//$NON-NLS-2$
755
}
756         } catch (InterruptedException JavaDoc e) {
757             return;
758         }
759     }
760
761
762     /**
763      * Returns the index of the first method that is a test method, i.e. excluding main, setUp() and tearDown().
764      * If none of the aforementioned method stubs is created, then 0 is returned. As such method stubs are created,
765      * this counter is incremented.
766      */

767     public int getIndexOfFirstMethod() {
768         return fIndexOfFirstTestMethod;
769     }
770
771     private boolean createTasks() {
772         return fPage2.getCreateTasksButtonSelection();
773     }
774
775     private void validateSuperClass() {
776         fMethodStubsButtons.setEnabled(2, true);//enable setUp() checkbox
777
fMethodStubsButtons.setEnabled(3, true);//enable tearDown() checkbox
778
String JavaDoc superClassName= getSuperClass();
779         if (superClassName == null || superClassName.trim().equals("")) { //$NON-NLS-1$
780
fSuperClassStatus= new JUnitStatus();
781             ((JUnitStatus)fSuperClassStatus).setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.empty")); //$NON-NLS-1$
782
return;
783         }
784         if (getPackageFragmentRoot() != null) { //$NON-NLS-1$
785
try {
786                 IType type= resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName);
787                 JUnitStatus status = new JUnitStatus();
788                 if (type == null) {
789                     /* TODO: is this a warning or error? */
790                     status.setWarning(WizardMessages.getString("NewTestClassWizPage.error.superclass.not_exist")); //$NON-NLS-1$
791
fSuperClassStatus= status;
792                 } else {
793                     if (type.isInterface()) {
794                         status.setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.is_interface")); //$NON-NLS-1$
795
fSuperClassStatus= status;
796                     }
797                     if (!TestSearchEngine.isTestImplementor(type)) {
798                         status.setError(WizardMessages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); //$NON-NLS-1$
799
fSuperClassStatus= status;
800                     } else {
801                         IMethod setupMethod= type.getMethod(SETUP, new String JavaDoc[] {});
802                         IMethod teardownMethod= type.getMethod(TEARDOWN, new String JavaDoc[] {});
803                         if (setupMethod.exists())
804                             fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags()));
805                         if (teardownMethod.exists())
806                             fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags()));
807                     }
808                 }
809             } catch (JavaModelException e) {
810                 JUnitPlugin.log(e);
811             }
812         }
813     }
814         
815     /**
816      * @see org.eclipse.jface.wizard.IWizardPage#canFlipToNextPage()
817      */

818     public boolean canFlipToNextPage() {
819         return isPageComplete() && getNextPage() != null && isNextPageValid();
820     }
821
822     protected boolean isNextPageValid() {
823         return !getClassToTestText().equals(""); //$NON-NLS-1$
824
}
825
826     private JUnitStatus validateClassToTest() {
827         IPackageFragmentRoot root= getPackageFragmentRoot();
828         IPackageFragment pack= getPackageFragment();
829         String JavaDoc classToTestName= getClassToTestText();
830         JUnitStatus status= new JUnitStatus();
831         
832         fClassToTest= null;
833         if (classToTestName.length() == 0) {
834             return status;
835         }
836         IStatus val= JavaConventions.validateJavaTypeName(classToTestName);
837 // if (!val.isOK()) {
838
if (val.getSeverity() == IStatus.ERROR) {
839             status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$
840
return status;
841         }
842         
843         if (root != null) {
844             try {
845                 IType type= resolveClassNameToType(root.getJavaProject(), pack, classToTestName);
846                 if (type == null) {
847                     //status.setWarning("Warning: "+typeLabel+" does not exist in current project.");
848
status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); //$NON-NLS-1$
849
return status;
850                 } else {
851                     if (type.isInterface()) {
852                         status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); //$NON-NLS-1$
853
}
854                     if (pack != null && !JavaModelUtil.isVisible(type, pack)) {
855                         status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.not_visible", new String JavaDoc[] {(type.isInterface())?WizardMessages.getString("Interface"):WizardMessages.getString("Class") , classToTestName})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
856
}
857                 }
858                 fClassToTest= type;
859             } catch (JavaModelException e) {
860                 status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); //$NON-NLS-1$
861
}
862         } else {
863             status.setError(""); //$NON-NLS-1$
864
}
865         return status;
866     }
867
868     private IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String JavaDoc classToTestName) throws JavaModelException {
869         IType type= null;
870         if (type == null && pack != null) {
871             String JavaDoc packName= pack.getElementName();
872             // search in own package
873
if (!pack.isDefaultPackage()) {
874                 type= jproject.findType(packName, classToTestName);
875             }
876             // search in java.lang
877
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
878
type= jproject.findType("java.lang", classToTestName); //$NON-NLS-1$
879
}
880         }
881         // search fully qualified
882
if (type == null) {
883             type= jproject.findType(classToTestName);
884         }
885         return type;
886     }
887     
888     /**
889      * Use the dialog store to restore widget values to the values that they held
890      * last time this wizard was used to completion
891      */

892     private void restoreWidgetValues() {
893         
894         IDialogSettings settings= getDialogSettings();
895         if (settings != null) {
896             boolean generateMain= settings.getBoolean(STORE_GENERATE_MAIN);
897             fMethodStubsButtons.setSelection(0, generateMain);
898             fMethodStubsButtons.setEnabled(1, generateMain);
899             fMethodStubsButtons.setSelection(1,settings.getBoolean(STORE_USE_TESTRUNNER));
900             try {
901                 fMethodStubsButtons.setComboSelection(settings.getInt(STORE_TESTRUNNER_TYPE));
902             } catch(NumberFormatException JavaDoc e) {}
903         }
904     }
905
906     /**
907      * Since Finish was pressed, write widget values to the dialog store so that they
908      * will persist into the next invocation of this wizard page
909      */

910     void saveWidgetValues() {
911         IDialogSettings settings= getDialogSettings();
912         if (settings != null) {
913             settings.put(STORE_GENERATE_MAIN, fMethodStubsButtons.isSelected(0));
914             settings.put(STORE_USE_TESTRUNNER, fMethodStubsButtons.isSelected(1));
915             settings.put(STORE_TESTRUNNER_TYPE, fMethodStubsButtons.getComboSelection());
916         }
917     }
918
919     public void aboutToRunOperation() {
920         fMainMethod= fMethodStubsButtons.getMainMethod(getTypeName());
921     }
922
923 }
924
Popular Tags