KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > junit > wizards > NewTestCaseWizardPageOne


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  * Sebastian Davids, sdavids@gmx.de - bug 38507
11  * Sebastian Davids, sdavids@gmx.de - 113998 [JUnit] New Test Case Wizard: Class Under Test Dialog -- allow Enums
12  *******************************************************************************/

13 package org.eclipse.jdt.junit.wizards;
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.Arrays JavaDoc;
17 import java.util.HashMap JavaDoc;
18 import java.util.List JavaDoc;
19 import java.util.ListIterator JavaDoc;
20 import java.util.Map JavaDoc;
21
22 import org.eclipse.core.runtime.CoreException;
23 import org.eclipse.core.runtime.IProgressMonitor;
24 import org.eclipse.core.runtime.IStatus;
25
26 import org.eclipse.swt.SWT;
27 import org.eclipse.swt.events.ModifyEvent;
28 import org.eclipse.swt.events.ModifyListener;
29 import org.eclipse.swt.events.SelectionAdapter;
30 import org.eclipse.swt.events.SelectionEvent;
31 import org.eclipse.swt.events.SelectionListener;
32 import org.eclipse.swt.layout.GridData;
33 import org.eclipse.swt.layout.GridLayout;
34 import org.eclipse.swt.widgets.Button;
35 import org.eclipse.swt.widgets.Composite;
36 import org.eclipse.swt.widgets.Label;
37 import org.eclipse.swt.widgets.Link;
38 import org.eclipse.swt.widgets.Text;
39
40 import org.eclipse.jface.dialogs.Dialog;
41 import org.eclipse.jface.dialogs.IDialogSettings;
42 import org.eclipse.jface.resource.JFaceResources;
43 import org.eclipse.jface.viewers.IStructuredSelection;
44 import org.eclipse.jface.window.Window;
45
46 import org.eclipse.ui.PlatformUI;
47 import org.eclipse.ui.dialogs.PreferencesUtil;
48 import org.eclipse.ui.dialogs.SelectionDialog;
49
50 import org.eclipse.jdt.core.IClassFile;
51 import org.eclipse.jdt.core.IClasspathEntry;
52 import org.eclipse.jdt.core.ICompilationUnit;
53 import org.eclipse.jdt.core.IJavaElement;
54 import org.eclipse.jdt.core.IJavaProject;
55 import org.eclipse.jdt.core.IMethod;
56 import org.eclipse.jdt.core.IPackageFragment;
57 import org.eclipse.jdt.core.IPackageFragmentRoot;
58 import org.eclipse.jdt.core.IType;
59 import org.eclipse.jdt.core.ITypeHierarchy;
60 import org.eclipse.jdt.core.JavaConventions;
61 import org.eclipse.jdt.core.JavaCore;
62 import org.eclipse.jdt.core.JavaModelException;
63 import org.eclipse.jdt.core.Signature;
64 import org.eclipse.jdt.core.search.IJavaSearchScope;
65 import org.eclipse.jdt.core.search.SearchEngine;
66
67 import org.eclipse.jdt.ui.CodeGeneration;
68 import org.eclipse.jdt.ui.IJavaElementSearchConstants;
69 import org.eclipse.jdt.ui.JavaElementLabels;
70 import org.eclipse.jdt.ui.JavaUI;
71 import org.eclipse.jdt.ui.wizards.NewTypeWizardPage;
72
73 import org.eclipse.jdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
74 import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
75
76 import org.eclipse.jdt.internal.junit.Messages;
77 import org.eclipse.jdt.internal.junit.buildpath.BuildPathSupport;
78 import org.eclipse.jdt.internal.junit.ui.IJUnitHelpContextIds;
79 import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
80 import org.eclipse.jdt.internal.junit.util.JUnitStatus;
81 import org.eclipse.jdt.internal.junit.util.JUnitStubUtility;
82 import org.eclipse.jdt.internal.junit.util.LayoutUtil;
83 import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
84 import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings;
85 import org.eclipse.jdt.internal.junit.wizards.MethodStubsSelectionButtonGroup;
86 import org.eclipse.jdt.internal.junit.wizards.WizardMessages;
87
88 /**
89  * The class <code>NewTestCaseWizardPageOne</code> contains controls and validation routines
90  * for the first page of the 'New JUnit TestCase Wizard'.
91  *
92  * Clients can use the page as-is and add it to their own wizard, or extend it to modify
93  * validation or add and remove controls.
94  *
95  * @since 3.1
96  */

97 public class NewTestCaseWizardPageOne extends NewTypeWizardPage {
98
99     private final static String JavaDoc PAGE_NAME= "NewTestCaseCreationWizardPage"; //$NON-NLS-1$
100

101     
102     /** Field ID of the class under test field. */
103     public final static String JavaDoc CLASS_UNDER_TEST= PAGE_NAME + ".classundertest"; //$NON-NLS-1$
104

105     /**
106      * Field ID of the Junit4 toggle
107      * @since 3.2
108      */

109     public final static String JavaDoc JUNIT4TOGGLE= PAGE_NAME + ".junit4toggle"; //$NON-NLS-1$
110

111     private static final String JavaDoc COMPLIANCE_PAGE_ID= "org.eclipse.jdt.ui.propertyPages.CompliancePreferencePage"; //$NON-NLS-1$
112
private static final String JavaDoc BUILD_PATH_PAGE_ID= "org.eclipse.jdt.ui.propertyPages.BuildPathsPropertyPage"; //$NON-NLS-1$
113
private static final Object JavaDoc BUILD_PATH_KEY_ADD_ENTRY= "add_classpath_entry"; //$NON-NLS-1$
114
private static final Object JavaDoc BUILD_PATH_BLOCK= "block_until_buildpath_applied"; //$NON-NLS-1$
115

116     private static final String JavaDoc KEY_NO_LINK= "PropertyAndPreferencePage.nolink"; //$NON-NLS-1$
117

118     private final static String JavaDoc QUESTION_MARK_TAG= "Q"; //$NON-NLS-1$
119
private final static String JavaDoc OF_TAG= "Of"; //$NON-NLS-1$
120

121     private final static String JavaDoc TEST_SUFFIX= "Test"; //$NON-NLS-1$
122
private final static String JavaDoc PREFIX= "test"; //$NON-NLS-1$
123

124     private final static String JavaDoc STORE_SETUP= PAGE_NAME + ".USE_SETUP"; //$NON-NLS-1$
125
private final static String JavaDoc STORE_TEARDOWN= PAGE_NAME + ".USE_TEARDOWN"; //$NON-NLS-1$
126
private final static String JavaDoc STORE_SETUP_CLASS= PAGE_NAME + ".USE_SETUPCLASS"; //$NON-NLS-1$
127
private final static String JavaDoc STORE_TEARDOWN_CLASS= PAGE_NAME + ".USE_TEARDOWNCLASS"; //$NON-NLS-1$
128
private final static String JavaDoc STORE_CONSTRUCTOR= PAGE_NAME + ".USE_CONSTRUCTOR"; //$NON-NLS-1$
129

130
131     private final static int IDX_SETUP_CLASS= 0;
132     private final static int IDX_TEARDOWN_CLASS= 1;
133     private final static int IDX_SETUP= 2;
134     private final static int IDX_TEARDOWN= 3;
135     private final static int IDX_CONSTRUCTOR= 4;
136     
137     private NewTestCaseWizardPageTwo fPage2;
138     private MethodStubsSelectionButtonGroup fMethodStubsButtons;
139
140     private String JavaDoc fClassUnderTestText; // model
141
private IType fClassUnderTest; // resolved model, can be null
142

143     private Text fClassUnderTestControl; // control
144
private IStatus fClassUnderTestStatus; // status
145

146     private Button fClassUnderTestButton;
147     private JavaTypeCompletionProcessor fClassToTestCompletionProcessor;
148
149
150     private Button fJUnit4Toggle;
151     private boolean fIsJunit4;
152     private IStatus fJunit4Status; // status
153
private boolean fIsJunit4Enabled;
154     private Link fLink;
155     private Label fImage;
156
157     /**
158      * Creates a new <code>NewTestCaseCreationWizardPage</code>.
159      * @param page2 The second page
160      *
161      * @since 3.1
162      */

163     public NewTestCaseWizardPageOne(NewTestCaseWizardPageTwo page2) {
164         super(true, PAGE_NAME);
165         fPage2= page2;
166         
167         setTitle(WizardMessages.NewTestCaseWizardPageOne_title);
168         setDescription(WizardMessages.NewTestCaseWizardPageOne_description);
169         
170         String JavaDoc[] buttonNames= new String JavaDoc[] {
171             /* IDX_SETUP_CLASS */ WizardMessages.NewTestCaseWizardPageOne_methodStub_setUpBeforeClass,
172             /* IDX_TEARDOWN_CLASS */ WizardMessages.NewTestCaseWizardPageOne_methodStub_tearDownAfterClass,
173             /* IDX_SETUP */ WizardMessages.NewTestCaseWizardPageOne_methodStub_setUp,
174             /* IDX_TEARDOWN */ WizardMessages.NewTestCaseWizardPageOne_methodStub_tearDown,
175             /* IDX_CONSTRUCTOR */ WizardMessages.NewTestCaseWizardPageOne_methodStub_constructor
176         };
177         enableCommentControl(true);
178         
179         fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 2);
180         fMethodStubsButtons.setLabelText(WizardMessages.NewTestCaseWizardPageOne_method_Stub_label);
181         
182         fClassToTestCompletionProcessor= new JavaTypeCompletionProcessor(false, false, true);
183
184         fClassUnderTestStatus= new JUnitStatus();
185         
186         fClassUnderTestText= ""; //$NON-NLS-1$
187

188         fJunit4Status= new JUnitStatus();
189         fIsJunit4= false;
190     }
191
192     /**
193      * Initialized the page with the current selection
194      * @param selection The selection
195      */

196     public void init(IStructuredSelection selection) {
197         IJavaElement element= getInitialJavaElement(selection);
198
199         initContainerPage(element);
200         initTypePage(element);
201         // put default class to test
202
if (element != null) {
203             IType classToTest= null;
204             // evaluate the enclosing type
205
IType typeInCompUnit= (IType) element.getAncestor(IJavaElement.TYPE);
206             if (typeInCompUnit != null) {
207                 if (typeInCompUnit.getCompilationUnit() != null) {
208                     classToTest= typeInCompUnit;
209                 }
210             } else {
211                 ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
212                 if (cu != null)
213                     classToTest= cu.findPrimaryType();
214                 else {
215                     if (element instanceof IClassFile) {
216                         try {
217                             IClassFile cf= (IClassFile) element;
218                             if (cf.isStructureKnown())
219                                 classToTest= cf.getType();
220                         } catch(JavaModelException e) {
221                             JUnitPlugin.log(e);
222                         }
223                     }
224                 }
225             }
226             if (classToTest != null) {
227                 try {
228                     if (!TestSearchEngine.isTestImplementor(classToTest)) {
229                         setClassUnderTest(classToTest.getFullyQualifiedName('.'));
230                     }
231                 } catch (JavaModelException e) {
232                     JUnitPlugin.log(e);
233                 }
234             }
235         }
236
237         restoreWidgetValues();
238         
239         boolean isJunit4= false;
240         if (element != null && element.getElementType() != IJavaElement.JAVA_MODEL) {
241             IJavaProject project= element.getJavaProject();
242             try {
243                 isJunit4= project.findType(JUnitPlugin.JUNIT4_ANNOTATION_NAME) != null;
244             } catch (JavaModelException e) {
245                 // ignore
246
}
247         }
248         setJUnit4(isJunit4, true);
249         
250         updateStatus(getStatusList());
251     }
252     
253     private IStatus junit4Changed() {
254         JUnitStatus status= new JUnitStatus();
255         return status;
256     }
257     
258     /**
259      * Specifies if the test should be created as JUnit 4 test.
260      * @param isJUnit4 If set, a Junit 4 test will be created
261      * @param isEnabled if <code>true</code> the modifier fields are
262      * editable; otherwise they are read-only
263      *
264      * @since 3.2
265      */

266     public void setJUnit4(boolean isJUnit4, boolean isEnabled) {
267         fIsJunit4Enabled= isEnabled;
268         if (fJUnit4Toggle != null && !fJUnit4Toggle.isDisposed()) {
269             fJUnit4Toggle.setSelection(isJUnit4);
270             fJUnit4Toggle.setEnabled(isEnabled);
271         }
272         internalSetJUnit4(isJUnit4);
273     }
274     
275     /**
276      * Returns <code>true</code> if the test should be created as Junit 4 test
277      * @return returns <code>true</code> if the test should be created as Junit 4 test
278      *
279      * @since 3.2
280      */

281     public boolean isJUnit4() {
282         return fIsJunit4;
283     }
284     
285     private void internalSetJUnit4(boolean isJUnit4) {
286         fIsJunit4= isJUnit4;
287         fJunit4Status= junit4Changed();
288         if (fIsJunit4) {
289             setSuperClass("java.lang.Object", false); //$NON-NLS-1$
290
} else {
291             setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true);
292         }
293         handleFieldChanged(JUNIT4TOGGLE);
294     }
295     
296     /* (non-Javadoc)
297      * @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
298      */

299     protected void handleFieldChanged(String JavaDoc fieldName) {
300         super.handleFieldChanged(fieldName);
301         if (fieldName.equals(CONTAINER)) {
302             fClassUnderTestStatus= classUnderTestChanged();
303             if (fClassUnderTestButton != null && !fClassUnderTestButton.isDisposed()) {
304                 fClassUnderTestButton.setEnabled(getPackageFragmentRoot() != null);
305             }
306             fJunit4Status= junit4Changed();
307             
308             updateBuildPathMessage();
309         } else if (fieldName.equals(JUNIT4TOGGLE)) {
310             updateBuildPathMessage();
311             fMethodStubsButtons.setEnabled(IDX_SETUP_CLASS, isJUnit4());
312             fMethodStubsButtons.setEnabled(IDX_TEARDOWN_CLASS, isJUnit4());
313             fMethodStubsButtons.setEnabled(IDX_CONSTRUCTOR, !isJUnit4());
314         }
315         updateStatus(getStatusList());
316     }
317
318     /**
319      * Returns all status to be consider for the validation. Clients can override.
320      * @return The list of status to consider for the validation.
321      */

322     protected IStatus[] getStatusList() {
323         return new IStatus[] {
324                 fContainerStatus,
325                 fPackageStatus,
326                 fTypeNameStatus,
327                 fClassUnderTestStatus,
328                 fModifierStatus,
329                 fSuperClassStatus,
330                 fJunit4Status
331         };
332     }
333     
334
335     /* (non-Javadoc)
336      * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
337      */

338     public void createControl(Composite parent) {
339         initializeDialogUnits(parent);
340         
341         Composite composite= new Composite(parent, SWT.NONE);
342         
343         int nColumns= 4;
344         
345         GridLayout layout= new GridLayout();
346         layout.numColumns= nColumns;
347         composite.setLayout(layout);
348         createJUnit4Controls(composite, nColumns);
349         createContainerControls(composite, nColumns);
350         createPackageControls(composite, nColumns);
351         createSeparator(composite, nColumns);
352         createTypeNameControls(composite, nColumns);
353         createSuperClassControls(composite, nColumns);
354         createMethodStubSelectionControls(composite, nColumns);
355         createCommentControls(composite, nColumns);
356         createSeparator(composite, nColumns);
357         createClassUnderTestControls(composite, nColumns);
358         createBuildPathConfigureControls(composite, nColumns);
359         
360         setControl(composite);
361             
362         //set default and focus
363
String JavaDoc classUnderTest= getClassUnderTestText();
364         if (classUnderTest.length() > 0) {
365             setTypeName(Signature.getSimpleName(classUnderTest)+TEST_SUFFIX, true);
366         }
367
368         Dialog.applyDialogFont(composite);
369         PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJUnitHelpContextIds.NEW_TESTCASE_WIZARD_PAGE);
370         
371         setFocus();
372     }
373
374     /**
375      * Creates the controls for the method stub selection buttons. Expects a <code>GridLayout</code> with
376      * at least 3 columns.
377      *
378      * @param composite the parent composite
379      * @param nColumns number of columns to span
380      */

381     protected void createMethodStubSelectionControls(Composite composite, int nColumns) {
382         LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns);
383         LayoutUtil.createEmptySpace(composite, 1);
384         LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1);
385     }
386
387     /**
388      * Creates the controls for the 'class under test' field. Expects a <code>GridLayout</code> with
389      * at least 3 columns.
390      *
391      * @param composite the parent composite
392      * @param nColumns number of columns to span
393      */

394     protected void createClassUnderTestControls(Composite composite, int nColumns) {
395         Label classUnderTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP);
396         classUnderTestLabel.setFont(composite.getFont());
397         classUnderTestLabel.setText(WizardMessages.NewTestCaseWizardPageOne_class_to_test_label);
398         classUnderTestLabel.setLayoutData(new GridData());
399
400         fClassUnderTestControl= new Text(composite, SWT.SINGLE | SWT.BORDER);
401         fClassUnderTestControl.setEnabled(true);
402         fClassUnderTestControl.setFont(composite.getFont());
403         fClassUnderTestControl.setText(fClassUnderTestText);
404         fClassUnderTestControl.addModifyListener(new ModifyListener() {
405             public void modifyText(ModifyEvent e) {
406                 internalSetClassUnderText(((Text) e.widget).getText());
407             }
408         });
409         GridData gd= new GridData();
410         gd.horizontalAlignment= GridData.FILL;
411         gd.grabExcessHorizontalSpace= true;
412         gd.horizontalSpan= nColumns - 2;
413         fClassUnderTestControl.setLayoutData(gd);
414         
415         fClassUnderTestButton= new Button(composite, SWT.PUSH);
416         fClassUnderTestButton.setText(WizardMessages.NewTestCaseWizardPageOne_class_to_test_browse);
417         fClassUnderTestButton.setEnabled(true);
418         fClassUnderTestButton.addSelectionListener(new SelectionListener() {
419             public void widgetDefaultSelected(SelectionEvent e) {
420                 classToTestButtonPressed();
421             }
422             public void widgetSelected(SelectionEvent e) {
423                 classToTestButtonPressed();
424             }
425         });
426         gd= new GridData();
427         gd.horizontalAlignment= GridData.FILL;
428         gd.grabExcessHorizontalSpace= false;
429         gd.horizontalSpan= 1;
430         gd.widthHint = LayoutUtil.getButtonWidthHint(fClassUnderTestButton);
431         fClassUnderTestButton.setLayoutData(gd);
432
433         ControlContentAssistHelper.createTextContentAssistant(fClassUnderTestControl, fClassToTestCompletionProcessor);
434     }
435     
436     /**
437      * Creates the controls for the JUnit 4 toggle control. Expects a <code>GridLayout</code> with
438      * at least 3 columns.
439      *
440      * @param composite the parent composite
441      * @param nColumns number of columns to span
442      *
443      * @since 3.2
444      */

445     protected void createJUnit4Controls(Composite composite, int nColumns) {
446         Composite inner= new Composite(composite, SWT.NONE);
447         inner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, nColumns, 1));
448         GridLayout layout= new GridLayout(2, false);
449         layout.marginHeight= 0;
450         layout.marginWidth= 0;
451         inner.setLayout(layout);
452         
453         SelectionAdapter listener= new SelectionAdapter() {
454             public void widgetSelected(SelectionEvent e) {
455                 boolean isSelected= ((Button) e.widget).getSelection();
456                 internalSetJUnit4(isSelected);
457             }
458         };
459         
460         Button junti3Toggle= new Button(inner, SWT.RADIO);
461         junti3Toggle.setText(WizardMessages.NewTestCaseWizardPageOne_junit3_radio_label);
462         junti3Toggle.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false, 1, 1));
463         junti3Toggle.setSelection(!fIsJunit4);
464         junti3Toggle.setEnabled(fIsJunit4Enabled);
465         
466         fJUnit4Toggle= new Button(inner, SWT.RADIO);
467         fJUnit4Toggle.setText(WizardMessages.NewTestCaseWizardPageOne_junit4_radio_label);
468         fJUnit4Toggle.setSelection(fIsJunit4);
469         fJUnit4Toggle.setEnabled(fIsJunit4Enabled);
470         fJUnit4Toggle.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false, 1, 1));
471         fJUnit4Toggle.addSelectionListener(listener);
472     }
473     
474     /**
475      * Creates the controls for the JUnit 4 toggle control. Expects a <code>GridLayout</code> with
476      * at least 3 columns.
477      *
478      * @param composite the parent composite
479      * @param nColumns number of columns to span
480      *
481      * @since 3.2
482      */

483     protected void createBuildPathConfigureControls(Composite composite, int nColumns) {
484         Composite inner= new Composite(composite, SWT.NONE);
485         inner.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false, nColumns, 1));
486         GridLayout layout= new GridLayout(2, false);
487         layout.marginWidth= 0;
488         layout.marginHeight= 0;
489         inner.setLayout(layout);
490         
491         fImage= new Label(inner, SWT.NONE);
492         fImage.setImage(JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_WARNING));
493         fImage.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1));
494
495         fLink= new Link(inner, SWT.WRAP);
496         fLink.setText("\n\n"); //$NON-NLS-1$
497
fLink.addSelectionListener(new SelectionAdapter() {
498             public void widgetSelected(SelectionEvent e) {
499                 performBuildpathConfiguration(e.text);
500             }
501         });
502         GridData gd= new GridData(GridData.FILL, GridData.BEGINNING, true, false, 1, 1);
503         gd.widthHint= convertWidthInCharsToPixels(60);
504         fLink.setLayoutData(gd);
505         updateBuildPathMessage();
506     }
507     
508     private void performBuildpathConfiguration(Object JavaDoc data) {
509         IPackageFragmentRoot root= getPackageFragmentRoot();
510         if (root == null) {
511             return; // should not happen. Link shouldn't be visible
512
}
513         IJavaProject javaProject= root.getJavaProject();
514         
515         if ("a3".equals(data)) { // add and configure JUnit 3 //$NON-NLS-1$
516
String JavaDoc id= BUILD_PATH_PAGE_ID;
517             Map JavaDoc input= new HashMap JavaDoc();
518             IClasspathEntry newEntry= BuildPathSupport.getJUnit3ClasspathEntry();
519             input.put(BUILD_PATH_KEY_ADD_ENTRY, newEntry);
520             input.put(BUILD_PATH_BLOCK, Boolean.TRUE);
521             PreferencesUtil.createPropertyDialogOn(getShell(), javaProject, id, new String JavaDoc[] { id }, input).open();
522         } else if ("a4".equals(data)) { // add and configure JUnit 4 //$NON-NLS-1$
523
String JavaDoc id= BUILD_PATH_PAGE_ID;
524             Map JavaDoc input= new HashMap JavaDoc();
525             IClasspathEntry newEntry= BuildPathSupport.getJUnit4ClasspathEntry();
526             input.put(BUILD_PATH_KEY_ADD_ENTRY, newEntry);
527             input.put(BUILD_PATH_BLOCK, Boolean.TRUE);
528             PreferencesUtil.createPropertyDialogOn(getShell(), javaProject, id, new String JavaDoc[] { id }, input).open();
529         } else if ("b".equals(data)) { // open build path //$NON-NLS-1$
530
String JavaDoc id= BUILD_PATH_PAGE_ID;
531             Map JavaDoc input= new HashMap JavaDoc();
532             input.put(BUILD_PATH_BLOCK, Boolean.TRUE);
533             PreferencesUtil.createPropertyDialogOn(getShell(), javaProject, id, new String JavaDoc[] { id }, input).open();
534         } else if ("c".equals(data)) { // open compliance //$NON-NLS-1$
535
String JavaDoc buildPath= BUILD_PATH_PAGE_ID;
536             String JavaDoc complianceId= COMPLIANCE_PAGE_ID;
537             Map JavaDoc input= new HashMap JavaDoc();
538             input.put(BUILD_PATH_BLOCK, Boolean.TRUE);
539             input.put(KEY_NO_LINK, Boolean.TRUE);
540             PreferencesUtil.createPropertyDialogOn(getShell(), javaProject, complianceId, new String JavaDoc[] { buildPath, complianceId }, data).open();
541         }
542         
543         updateBuildPathMessage();
544     }
545
546     private void updateBuildPathMessage() {
547         if (fLink == null || fLink.isDisposed()) {
548             return;
549         }
550         
551         String JavaDoc message= null;
552         IPackageFragmentRoot root= getPackageFragmentRoot();
553         if (root != null) {
554             try {
555                 IJavaProject project= root.getJavaProject();
556                 if (project.exists()) {
557                     if (isJUnit4()) {
558                         if (!JUnitStubUtility.is50OrHigher(project)) {
559                             message= WizardMessages.NewTestCaseWizardPageOne_linkedtext_java5required;
560                         } else if (project.findType(JUnitPlugin.JUNIT4_ANNOTATION_NAME) == null) {
561                             message= Messages.format(WizardMessages.NewTestCaseWizardPageOne_linkedtext_junit4_notonbuildpath, project.getElementName());
562                         }
563                     } else {
564                         if (project.findType(JUnitPlugin.TEST_SUPERCLASS_NAME) == null) {
565                             message= Messages.format(WizardMessages.NewTestCaseWizardPageOne_linkedtext_junit3_notonbuildpath, project.getElementName());
566                         }
567                     }
568                 }
569             } catch (JavaModelException e) {
570             }
571         }
572         fLink.setVisible(message != null);
573         fImage.setVisible(message != null);
574         
575         if (message != null) {
576             fLink.setText(message);
577         }
578     }
579     
580
581     private void classToTestButtonPressed() {
582         IType type= chooseClassToTestType();
583         if (type != null) {
584             setClassUnderTest(type.getFullyQualifiedName('.'));
585         }
586     }
587
588     private IType chooseClassToTestType() {
589         IPackageFragmentRoot root= getPackageFragmentRoot();
590         if (root == null)
591             return null;
592
593         IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
594         IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
595         
596         try {
597             SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES_AND_ENUMS, false, getClassUnderTestText());
598             dialog.setTitle(WizardMessages.NewTestCaseWizardPageOne_class_to_test_dialog_title);
599             dialog.setMessage(WizardMessages.NewTestCaseWizardPageOne_class_to_test_dialog_message);
600             if (dialog.open() == Window.OK) {
601                 Object JavaDoc[] resultArray= dialog.getResult();
602                 if (resultArray != null && resultArray.length > 0)
603                     return (IType) resultArray[0];
604             }
605         } catch (JavaModelException e) {
606             JUnitPlugin.log(e);
607         }
608         return null;
609     }
610
611     /* (non-Javadoc)
612      * @see org.eclipse.jdt.ui.wizards.NewTypeWizardPage#packageChanged()
613      */

614     protected IStatus packageChanged() {
615         IStatus status= super.packageChanged();
616         fClassToTestCompletionProcessor.setPackageFragment(getPackageFragment());
617         return status;
618     }
619     
620     /**
621      * Hook method that gets called when the class under test has changed. The method class under test
622      * returns the status of the validation.
623      * <p>
624      * Subclasses may extend this method to perform their own validation.
625      * </p>
626      *
627      * @return the status of the validation
628      */

629     protected IStatus classUnderTestChanged() {
630         JUnitStatus status= new JUnitStatus();
631         
632         
633         fClassUnderTest= null;
634         
635         IPackageFragmentRoot root= getPackageFragmentRoot();
636         if (root == null) {
637             return status;
638         }
639         
640         String JavaDoc classToTestName= getClassUnderTestText();
641         if (classToTestName.length() == 0) {
642             return status;
643         }
644         IJavaProject javaProject= root.getJavaProject();
645         String JavaDoc sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
646         String JavaDoc compliance= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
647         
648         IStatus val= JavaConventions.validateJavaTypeName(classToTestName, sourceLevel, compliance);
649         if (val.getSeverity() == IStatus.ERROR) {
650             status.setError(WizardMessages.NewTestCaseWizardPageOne_error_class_to_test_not_valid);
651             return status;
652         }
653         
654         IPackageFragment pack= getPackageFragment(); // can be null
655
try {
656             IType type= resolveClassNameToType(root.getJavaProject(), pack, classToTestName);
657             if (type == null) {
658                 status.setError(WizardMessages.NewTestCaseWizardPageOne_error_class_to_test_not_exist);
659                 return status;
660             }
661             if (type.isInterface()) {
662                 status.setWarning(Messages.format(WizardMessages.NewTestCaseWizardPageOne_warning_class_to_test_is_interface, classToTestName));
663             }
664             
665             if (pack != null && !JUnitStubUtility.isVisible(type, pack)) {
666                 status.setWarning(Messages.format(WizardMessages.NewTestCaseWizardPageOne_warning_class_to_test_not_visible, classToTestName));
667             }
668             fClassUnderTest= type;
669             fPage2.setClassUnderTest(fClassUnderTest);
670         } catch (JavaModelException e) {
671             status.setError(WizardMessages.NewTestCaseWizardPageOne_error_class_to_test_not_valid);
672         }
673         return status;
674     }
675
676     /**
677      * Returns the content of the class to test text field.
678      *
679      * @return the name of the class to test
680      */

681     public String JavaDoc getClassUnderTestText() {
682         return fClassUnderTestText;
683     }
684     
685     /**
686      * Returns the class to be tested.
687      *
688      * @return the class under test or <code>null</code> if the entered values are not valid
689      */

690     public IType getClassUnderTest() {
691         return fClassUnderTest;
692     }
693     
694     /**
695      * Sets the name of the class under test.
696      *
697      * @param name The name to set
698      */

699     public void setClassUnderTest(String JavaDoc name) {
700         if (fClassUnderTestControl != null && !fClassUnderTestControl.isDisposed()) {
701             fClassUnderTestControl.setText(name);
702         }
703         internalSetClassUnderText(name);
704     }
705     
706     private void internalSetClassUnderText(String JavaDoc name) {
707         fClassUnderTestText= name;
708         fClassUnderTestStatus= classUnderTestChanged();
709         handleFieldChanged(CLASS_UNDER_TEST);
710     }
711
712     /* (non-Javadoc)
713      * @see org.eclipse.jdt.ui.wizards.NewTypeWizardPage#createTypeMembers(org.eclipse.jdt.core.IType, org.eclipse.jdt.ui.wizards.NewTypeWizardPage.ImportsManager, org.eclipse.core.runtime.IProgressMonitor)
714      */

715     protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
716         if (fMethodStubsButtons.isSelected(IDX_CONSTRUCTOR))
717             createConstructor(type, imports);
718         
719         if (fMethodStubsButtons.isSelected(IDX_SETUP_CLASS)) {
720             createSetUpClass(type, imports);
721         }
722         
723         if (fMethodStubsButtons.isSelected(IDX_TEARDOWN_CLASS)) {
724             createTearDownClass(type, imports);
725         }
726         
727         if (fMethodStubsButtons.isSelected(IDX_SETUP)) {
728             createSetUp(type, imports);
729         }
730         
731         if (fMethodStubsButtons.isSelected(IDX_TEARDOWN)) {
732             createTearDown(type, imports);
733         }
734
735         if (fClassUnderTest != null) {
736             createTestMethodStubs(type, imports);
737         }
738         
739         if (isJUnit4()) {
740             imports.addStaticImport("org.junit.Assert", "*", false); //$NON-NLS-1$ //$NON-NLS-2$
741
}
742         
743     }
744
745     private void createConstructor(IType type, ImportsManager imports) throws CoreException {
746         ITypeHierarchy typeHierarchy= null;
747         IType[] superTypes= null;
748         String JavaDoc content;
749         IMethod methodTemplate= null;
750         if (type.exists()) {
751             typeHierarchy= type.newSupertypeHierarchy(null);
752             superTypes= typeHierarchy.getAllSuperclasses(type);
753             for (int i= 0; i < superTypes.length; i++) {
754                 if (superTypes[i].exists()) {
755                     IMethod constrMethod= superTypes[i].getMethod(superTypes[i].getElementName(), new String JavaDoc[] {"Ljava.lang.String;"}); //$NON-NLS-1$
756
if (constrMethod.exists() && constrMethod.isConstructor()) {
757                         methodTemplate= constrMethod;
758                         break;
759                     }
760                 }
761             }
762         }
763         GenStubSettings settings= JUnitStubUtility.getCodeGenerationSettings(type.getJavaProject());
764         settings.createComments= isAddComments();
765         
766         if (methodTemplate != null) {
767             settings.callSuper= true;
768             settings.methodOverwrites= true;
769             content= JUnitStubUtility.genStub(type.getCompilationUnit(), getTypeName(), methodTemplate, settings, null, imports);
770         } else {
771             final String JavaDoc delimiter= getLineDelimiter();
772             StringBuffer JavaDoc buffer= new StringBuffer JavaDoc(32);
773             buffer.append("public "); //$NON-NLS-1$
774
buffer.append(getTypeName());
775             buffer.append('(');
776             if (!isJUnit4()) {
777                 buffer.append(imports.addImport("java.lang.String")).append(" name"); //$NON-NLS-1$ //$NON-NLS-2$
778
}
779             buffer.append(") {"); //$NON-NLS-1$
780
buffer.append(delimiter);
781             if (!isJUnit4()) {
782                 buffer.append("super(name);").append(delimiter); //$NON-NLS-1$
783
}
784             buffer.append('}');
785             buffer.append(delimiter);
786             content= buffer.toString();
787         }
788         type.createMethod(content, null, true, null);
789     }
790
791     private IMethod findInHierarchy(IType type, String JavaDoc methodName) throws JavaModelException {
792         ITypeHierarchy typeHierarchy= null;
793         IType[] superTypes= null;
794         if (type.exists()) {
795             typeHierarchy= type.newSupertypeHierarchy(null);
796             superTypes= typeHierarchy.getAllSuperclasses(type);
797             for (int i= 0; i < superTypes.length; i++) {
798                 if (superTypes[i].exists()) {
799                     IMethod testMethod= superTypes[i].getMethod(methodName, new String JavaDoc[] {});
800                     if (testMethod.exists()) {
801                         return testMethod;
802                     }
803                 }
804             }
805         }
806         return null;
807     }
808     
809     private void createSetupStubs(IType type, String JavaDoc methodName, boolean isStatic, String JavaDoc annotationType, ImportsManager imports) throws CoreException {
810         String JavaDoc content= null;
811         IMethod methodTemplate= findInHierarchy(type, methodName);
812         String JavaDoc annotation= null;
813         if (isJUnit4()) {
814             annotation= '@' + imports.addImport(annotationType);
815         }
816         
817         GenStubSettings settings= JUnitStubUtility.getCodeGenerationSettings(type.getJavaProject());
818         settings.createComments= isAddComments();
819         
820         if (methodTemplate != null) {
821             settings.callSuper= true;
822             settings.methodOverwrites= true;
823             content= JUnitStubUtility.genStub(type.getCompilationUnit(), getTypeName(), methodTemplate, settings, annotation, imports);
824         } else {
825             final String JavaDoc delimiter= getLineDelimiter();
826             StringBuffer JavaDoc buffer= new StringBuffer JavaDoc();
827             if (settings.createComments) {
828                 String JavaDoc[] excSignature= { Signature.createTypeSignature("java.lang.Exception", true) }; //$NON-NLS-1$
829
String JavaDoc comment= CodeGeneration.getMethodComment(type.getCompilationUnit(), type.getElementName(), methodName, new String JavaDoc[0], excSignature, Signature.SIG_VOID, null, delimiter);
830                 if (comment != null) {
831                     buffer.append(comment);
832                 }
833             }
834             if (annotation != null) {
835                 buffer.append(annotation).append(delimiter);
836             }
837             
838             if (isJUnit4()) {
839                 buffer.append("public "); //$NON-NLS-1$
840
} else {
841                 buffer.append("protected "); //$NON-NLS-1$
842
}
843             if (isStatic) {
844                 buffer.append("static "); //$NON-NLS-1$
845
}
846             buffer.append("void "); //$NON-NLS-1$
847
buffer.append(methodName);
848             buffer.append("() throws "); //$NON-NLS-1$
849
buffer.append(imports.addImport("java.lang.Exception")); //$NON-NLS-1$
850
buffer.append(" {}"); //$NON-NLS-1$
851
buffer.append(delimiter);
852             content= buffer.toString();
853         }
854         type.createMethod(content, null, false, null);
855     }
856     
857     
858     
859     private void createSetUp(IType type, ImportsManager imports) throws CoreException {
860         createSetupStubs(type, "setUp", false, "org.junit.Before", imports); //$NON-NLS-1$ //$NON-NLS-2$
861
}
862     
863     private void createTearDown(IType type, ImportsManager imports) throws CoreException {
864         createSetupStubs(type, "tearDown", false, "org.junit.After", imports); //$NON-NLS-1$ //$NON-NLS-2$
865
}
866     
867     private void createSetUpClass(IType type, ImportsManager imports) throws CoreException {
868         createSetupStubs(type, "setUpBeforeClass", true, "org.junit.BeforeClass", imports); //$NON-NLS-1$ //$NON-NLS-2$
869
}
870     
871     private void createTearDownClass(IType type, ImportsManager imports) throws CoreException {
872         createSetupStubs(type, "tearDownAfterClass", true, "org.junit.AfterClass", imports); //$NON-NLS-1$ //$NON-NLS-2$
873
}
874
875     private void createTestMethodStubs(IType type, ImportsManager imports) throws CoreException {
876         IMethod[] methods= fPage2.getCheckedMethods();
877         if (methods.length == 0)
878             return;
879         /* find overloaded methods */
880         IMethod[] allMethodsArray= fPage2.getAllMethods();
881         List JavaDoc allMethods= new ArrayList JavaDoc();
882         allMethods.addAll(Arrays.asList(allMethodsArray));
883         List JavaDoc overloadedMethods= getOverloadedMethods(allMethods);
884             
885         /* used when for example both sum and Sum methods are present. Then
886          * sum -> testSum
887          * Sum -> testSum1
888          */

889         List JavaDoc names= new ArrayList JavaDoc();
890         for (int i = 0; i < methods.length; i++) {
891             IMethod method= methods[i];
892             String JavaDoc elementName= method.getElementName();
893             StringBuffer JavaDoc name= new StringBuffer JavaDoc(PREFIX).append(Character.toUpperCase(elementName.charAt(0))).append(elementName.substring(1));
894             StringBuffer JavaDoc buffer= new StringBuffer JavaDoc();
895     
896             final boolean contains= overloadedMethods.contains(method);
897             if (contains)
898                 appendParameterNamesToMethodName(name, method.getParameterTypes());
899
900             replaceIllegalCharacters(name);
901             /* void foo(java.lang.StringBuffer sb) {}
902              * void foo(mypackage1.StringBuffer sb) {}
903              * void foo(mypackage2.StringBuffer sb) {}
904              * ->
905              * testFooStringBuffer()
906              * testFooStringBuffer1()
907              * testFooStringBuffer2()
908              */

909             String JavaDoc testName= name.toString();
910             if (names.contains(testName)) {
911                 int suffix= 1;
912                 while (names.contains(testName + Integer.toString(suffix)))
913                     suffix++;
914                 name.append(Integer.toString(suffix));
915             }
916             testName= name.toString();
917             names.add(testName);
918             
919             if (isAddComments()) {
920                 appendMethodComment(buffer, method);
921             }
922             if (isJUnit4()) {
923                 buffer.append('@').append(imports.addImport(JUnitPlugin.JUNIT4_ANNOTATION_NAME)).append(getLineDelimiter());
924             }
925             
926             buffer.append("public ");//$NON-NLS-1$
927
if (fPage2.getCreateFinalMethodStubsButtonSelection())
928                 buffer.append("final "); //$NON-NLS-1$
929
buffer.append("void ");//$NON-NLS-1$
930
buffer.append(testName);
931             buffer.append("()");//$NON-NLS-1$
932
appendTestMethodBody(buffer, testName, method, type.getCompilationUnit(), imports);
933             type.createMethod(buffer.toString(), null, false, null);
934         }
935     }
936
937     private void replaceIllegalCharacters(StringBuffer JavaDoc buffer) {
938         char character= 0;
939         for (int index= buffer.length() - 1; index >= 0; index--) {
940             character= buffer.charAt(index);
941             if (Character.isWhitespace(character))
942                 buffer.deleteCharAt(index);
943             else if (character == '<')
944                 buffer.replace(index, index + 1, OF_TAG);
945             else if (character == '?')
946                 buffer.replace(index, index + 1, QUESTION_MARK_TAG);
947             else if (!Character.isJavaIdentifierPart(character))
948                 buffer.deleteCharAt(index);
949         }
950     }
951
952     private String JavaDoc getLineDelimiter() throws JavaModelException{
953         IType classToTest= getClassUnderTest();
954         
955         if (classToTest != null && classToTest.exists() && classToTest.getCompilationUnit() != null)
956             return classToTest.getCompilationUnit().findRecommendedLineSeparator();
957         
958         return getPackageFragment().findRecommendedLineSeparator();
959     }
960
961     private void appendTestMethodBody(StringBuffer JavaDoc buffer, String JavaDoc name, IMethod method, ICompilationUnit targetCu, ImportsManager imports) throws CoreException {
962         final String JavaDoc delimiter= getLineDelimiter();
963         buffer.append('{').append(delimiter);
964         String JavaDoc todoTask= ""; //$NON-NLS-1$
965
if (fPage2.isCreateTasks()) {
966             String JavaDoc todoTaskTag= JUnitStubUtility.getTodoTaskTag(targetCu.getJavaProject());
967             if (todoTaskTag != null) {
968                 todoTask= " // " + todoTaskTag; //$NON-NLS-1$
969
}
970         }
971         String JavaDoc message= WizardMessages.NewTestCaseWizardPageOne_not_yet_implemented_string;
972         buffer.append(Messages.format("fail(\"{0}\");", message)).append(todoTask).append(delimiter); //$NON-NLS-1$
973

974         buffer.append('}').append(delimiter);
975     }
976
977     private void appendParameterNamesToMethodName(StringBuffer JavaDoc buffer, String JavaDoc[] parameters) {
978         for (int i= 0; i < parameters.length; i++) {
979             final StringBuffer JavaDoc buf= new StringBuffer JavaDoc(Signature.getSimpleName(Signature.toString(Signature.getElementType(parameters[i]))));
980             final char character= buf.charAt(0);
981             if (buf.length() > 0 && !Character.isUpperCase(character))
982                 buf.setCharAt(0, Character.toUpperCase(character));
983             buffer.append(buf.toString());
984             for (int j= 0, arrayCount= Signature.getArrayCount(parameters[i]); j < arrayCount; j++) {
985                 buffer.append("Array"); //$NON-NLS-1$
986
}
987         }
988     }
989
990     private void appendMethodComment(StringBuffer JavaDoc buffer, IMethod method) throws JavaModelException {
991         final String JavaDoc delimiter= getLineDelimiter();
992         final StringBuffer JavaDoc buf= new StringBuffer JavaDoc("{@link "); //$NON-NLS-1$
993
JavaElementLabels.getTypeLabel(method.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED, buf);
994         buf.append('#');
995         buf.append(method.getElementName());
996         buf.append('(');
997         String JavaDoc[] paramTypes= JUnitStubUtility.getParameterTypeNamesForSeeTag(method);
998         for (int i= 0; i < paramTypes.length; i++) {
999             if (i != 0) {
1000                buf.append(", "); //$NON-NLS-1$
1001
}
1002            buf.append(paramTypes[i]);
1003            
1004        }
1005        buf.append(')');
1006        buf.append('}');
1007        
1008        buffer.append("/**");//$NON-NLS-1$
1009
buffer.append(delimiter);
1010        buffer.append(" * ");//$NON-NLS-1$
1011
buffer.append(Messages.format(WizardMessages.NewTestCaseWizardPageOne_comment_class_to_test, buf.toString()));
1012        buffer.append(delimiter);
1013        buffer.append(" */");//$NON-NLS-1$
1014
buffer.append(delimiter);
1015    }
1016    
1017
1018    private List JavaDoc getOverloadedMethods(List JavaDoc allMethods) {
1019        List JavaDoc overloadedMethods= new ArrayList JavaDoc();
1020        for (int i= 0; i < allMethods.size(); i++) {
1021            IMethod current= (IMethod) allMethods.get(i);
1022            String JavaDoc currentName= current.getElementName();
1023            boolean currentAdded= false;
1024            for (ListIterator JavaDoc iter= allMethods.listIterator(i+1); iter.hasNext(); ) {
1025                IMethod iterMethod= (IMethod) iter.next();
1026                if (iterMethod.getElementName().equals(currentName)) {
1027                    //method is overloaded
1028
if (!currentAdded) {
1029                        overloadedMethods.add(current);
1030                        currentAdded= true;
1031                    }
1032                    overloadedMethods.add(iterMethod);
1033                    iter.remove();
1034                }
1035            }
1036        }
1037        return overloadedMethods;
1038    }
1039
1040    /* (non-Javadoc)
1041     * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
1042     */

1043    public void setVisible(boolean visible) {
1044        super.setVisible(visible);
1045        if (!visible) {
1046            saveWidgetValues();
1047        }
1048        
1049        //if (visible) setFocus();
1050
}
1051    
1052    /**
1053     * The method is called when the container has changed to validate if the project
1054     * is suited for the JUnit test class. Clients can override to modify or remove that validation.
1055     *
1056     * @return the status of the validation
1057     */

1058    protected IStatus validateIfJUnitProject() {
1059        JUnitStatus status= new JUnitStatus();
1060        IPackageFragmentRoot root= getPackageFragmentRoot();
1061        if (root != null) {
1062            try {
1063                IJavaProject project= root.getJavaProject();
1064                if (project.exists()) {
1065                    if (isJUnit4()) {
1066                        if (!JUnitStubUtility.is50OrHigher(project)) {
1067                            status.setError(WizardMessages.NewTestCaseWizardPageOne_error_java5required);
1068                            return status;
1069                        }
1070                        if (project.findType(JUnitPlugin.JUNIT4_ANNOTATION_NAME) == null) {
1071                            status.setWarning(WizardMessages.NewTestCaseWizardPageOne__error_junit4NotOnbuildpath);
1072                            return status;
1073                        }
1074                    } else {
1075                        if (project.findType(JUnitPlugin.TEST_SUPERCLASS_NAME) == null) {
1076                            status.setWarning(WizardMessages.NewTestCaseWizardPageOne_error_junitNotOnbuildpath);
1077                            return status;
1078                        }
1079                    }
1080                }
1081            } catch (JavaModelException e) {
1082            }
1083        }
1084        return status;
1085    }
1086
1087    /* (non-Javadoc)
1088     * @see org.eclipse.jdt.ui.wizards.NewTypeWizardPage#superClassChanged()
1089     */

1090    protected IStatus superClassChanged() {
1091        // replaces the super class validation of of the normal type wizard
1092
if (isJUnit4()) {
1093            return new JUnitStatus();
1094        }
1095        
1096        String JavaDoc superClassName= getSuperClass();
1097        JUnitStatus status= new JUnitStatus();
1098        if (superClassName == null || superClassName.trim().equals("")) { //$NON-NLS-1$
1099
status.setError(WizardMessages.NewTestCaseWizardPageOne_error_superclass_empty);
1100            return status;
1101        }
1102        if (getPackageFragmentRoot() != null) {
1103            try {
1104                IType type= resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName);
1105                if (type == null) {
1106                    status.setWarning(WizardMessages.NewTestCaseWizardPageOne_error_superclass_not_exist);
1107                    return status;
1108                }
1109                if (type.isInterface()) {
1110                    status.setError(WizardMessages.NewTestCaseWizardPageOne_error_superclass_is_interface);
1111                    return status;
1112                }
1113                if (!TestSearchEngine.isTestImplementor(type)) { // TODO: expensive!
1114
status.setError(Messages.format(WizardMessages.NewTestCaseWizardPageOne_error_superclass_not_implementing_test_interface, JUnitPlugin.TEST_INTERFACE_NAME));
1115                    return status;
1116                }
1117            } catch (JavaModelException e) {
1118                JUnitPlugin.log(e);
1119            }
1120        }
1121        return status;
1122    }
1123        
1124    /* (non-Javadoc)
1125     * @see org.eclipse.jface.wizard.IWizardPage#canFlipToNextPage()
1126     */

1127    public boolean canFlipToNextPage() {
1128        return super.canFlipToNextPage() && getClassUnderTest() != null;
1129    }
1130
1131    private IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String JavaDoc classToTestName) throws JavaModelException {
1132        if (!jproject.exists()) {
1133            return null;
1134        }
1135        
1136        IType type= jproject.findType(classToTestName);
1137        
1138        // search in current package
1139
if (type == null && pack != null && !pack.isDefaultPackage()) {
1140            type= jproject.findType(pack.getElementName(), classToTestName);
1141        }
1142        
1143        // search in java.lang
1144
if (type == null) {
1145            type= jproject.findType("java.lang", classToTestName); //$NON-NLS-1$
1146
}
1147        return type;
1148    }
1149    
1150    /**
1151     * Use the dialog store to restore widget values to the values that they held
1152     * last time this wizard was used to completion
1153     */

1154    private void restoreWidgetValues() {
1155        IDialogSettings settings= getDialogSettings();
1156        if (settings != null) {
1157            fMethodStubsButtons.setSelection(IDX_SETUP, settings.getBoolean(STORE_SETUP));
1158            fMethodStubsButtons.setSelection(IDX_TEARDOWN, settings.getBoolean(STORE_TEARDOWN));
1159            fMethodStubsButtons.setSelection(IDX_SETUP_CLASS, settings.getBoolean(STORE_SETUP_CLASS));
1160            fMethodStubsButtons.setSelection(IDX_TEARDOWN_CLASS, settings.getBoolean(STORE_TEARDOWN_CLASS));
1161            fMethodStubsButtons.setSelection(IDX_CONSTRUCTOR, settings.getBoolean(STORE_CONSTRUCTOR));
1162        } else {
1163            fMethodStubsButtons.setSelection(IDX_SETUP, false); //setUp
1164
fMethodStubsButtons.setSelection(IDX_TEARDOWN, false); //tearDown
1165
fMethodStubsButtons.setSelection(IDX_SETUP_CLASS, false); //setUpBeforeClass
1166
fMethodStubsButtons.setSelection(IDX_TEARDOWN_CLASS, false); //setUpAfterClass
1167
fMethodStubsButtons.setSelection(IDX_CONSTRUCTOR, false); //constructor
1168
}
1169    }
1170
1171    /**
1172     * Since Finish was pressed, write widget values to the dialog store so that they
1173     * will persist into the next invocation of this wizard page
1174     */

1175    private void saveWidgetValues() {
1176        IDialogSettings settings= getDialogSettings();
1177        if (settings != null) {
1178            settings.put(STORE_SETUP, fMethodStubsButtons.isSelected(IDX_SETUP));
1179            settings.put(STORE_TEARDOWN, fMethodStubsButtons.isSelected(IDX_TEARDOWN));
1180            settings.put(STORE_SETUP_CLASS, fMethodStubsButtons.isSelected(IDX_SETUP_CLASS));
1181            settings.put(STORE_TEARDOWN_CLASS, fMethodStubsButtons.isSelected(IDX_TEARDOWN_CLASS));
1182            settings.put(STORE_CONSTRUCTOR, fMethodStubsButtons.isSelected(IDX_CONSTRUCTOR));
1183        }
1184    }
1185
1186}
1187
Popular Tags