1 13 package org.eclipse.jdt.junit.wizards; 14 15 import java.util.ArrayList ; 16 import java.util.Arrays ; 17 import java.util.HashMap ; 18 import java.util.List ; 19 import java.util.ListIterator ; 20 import java.util.Map ; 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 97 public class NewTestCaseWizardPageOne extends NewTypeWizardPage { 98 99 private final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; 101 102 103 public final static String CLASS_UNDER_TEST= PAGE_NAME + ".classundertest"; 105 109 public final static String JUNIT4TOGGLE= PAGE_NAME + ".junit4toggle"; 111 private static final String COMPLIANCE_PAGE_ID= "org.eclipse.jdt.ui.propertyPages.CompliancePreferencePage"; private static final String BUILD_PATH_PAGE_ID= "org.eclipse.jdt.ui.propertyPages.BuildPathsPropertyPage"; private static final Object BUILD_PATH_KEY_ADD_ENTRY= "add_classpath_entry"; private static final Object BUILD_PATH_BLOCK= "block_until_buildpath_applied"; 116 private static final String KEY_NO_LINK= "PropertyAndPreferencePage.nolink"; 118 private final static String QUESTION_MARK_TAG= "Q"; private final static String OF_TAG= "Of"; 121 private final static String TEST_SUFFIX= "Test"; private final static String PREFIX= "test"; 124 private final static String STORE_SETUP= PAGE_NAME + ".USE_SETUP"; private final static String STORE_TEARDOWN= PAGE_NAME + ".USE_TEARDOWN"; private final static String STORE_SETUP_CLASS= PAGE_NAME + ".USE_SETUPCLASS"; private final static String STORE_TEARDOWN_CLASS= PAGE_NAME + ".USE_TEARDOWNCLASS"; private final static String STORE_CONSTRUCTOR= PAGE_NAME + ".USE_CONSTRUCTOR"; 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 fClassUnderTestText; private IType fClassUnderTest; 143 private Text fClassUnderTestControl; private IStatus fClassUnderTestStatus; 146 private Button fClassUnderTestButton; 147 private JavaTypeCompletionProcessor fClassToTestCompletionProcessor; 148 149 150 private Button fJUnit4Toggle; 151 private boolean fIsJunit4; 152 private IStatus fJunit4Status; private boolean fIsJunit4Enabled; 154 private Link fLink; 155 private Label fImage; 156 157 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 [] buttonNames= new String [] { 171 WizardMessages.NewTestCaseWizardPageOne_methodStub_setUpBeforeClass, 172 WizardMessages.NewTestCaseWizardPageOne_methodStub_tearDownAfterClass, 173 WizardMessages.NewTestCaseWizardPageOne_methodStub_setUp, 174 WizardMessages.NewTestCaseWizardPageOne_methodStub_tearDown, 175 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= ""; 188 fJunit4Status= new JUnitStatus(); 189 fIsJunit4= false; 190 } 191 192 196 public void init(IStructuredSelection selection) { 197 IJavaElement element= getInitialJavaElement(selection); 198 199 initContainerPage(element); 200 initTypePage(element); 201 if (element != null) { 203 IType classToTest= null; 204 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 } 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 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 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); } else { 291 setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); 292 } 293 handleFieldChanged(JUNIT4TOGGLE); 294 } 295 296 299 protected void handleFieldChanged(String 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 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 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 String 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 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 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 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 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"); 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 data) { 509 IPackageFragmentRoot root= getPackageFragmentRoot(); 510 if (root == null) { 511 return; } 513 IJavaProject javaProject= root.getJavaProject(); 514 515 if ("a3".equals(data)) { String id= BUILD_PATH_PAGE_ID; 517 Map input= new HashMap (); 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 [] { id }, input).open(); 522 } else if ("a4".equals(data)) { String id= BUILD_PATH_PAGE_ID; 524 Map input= new HashMap (); 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 [] { id }, input).open(); 529 } else if ("b".equals(data)) { String id= BUILD_PATH_PAGE_ID; 531 Map input= new HashMap (); 532 input.put(BUILD_PATH_BLOCK, Boolean.TRUE); 533 PreferencesUtil.createPropertyDialogOn(getShell(), javaProject, id, new String [] { id }, input).open(); 534 } else if ("c".equals(data)) { String buildPath= BUILD_PATH_PAGE_ID; 536 String complianceId= COMPLIANCE_PAGE_ID; 537 Map input= new HashMap (); 538 input.put(BUILD_PATH_BLOCK, Boolean.TRUE); 539 input.put(KEY_NO_LINK, Boolean.TRUE); 540 PreferencesUtil.createPropertyDialogOn(getShell(), javaProject, complianceId, new String [] { 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 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 [] 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 614 protected IStatus packageChanged() { 615 IStatus status= super.packageChanged(); 616 fClassToTestCompletionProcessor.setPackageFragment(getPackageFragment()); 617 return status; 618 } 619 620 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 classToTestName= getClassUnderTestText(); 641 if (classToTestName.length() == 0) { 642 return status; 643 } 644 IJavaProject javaProject= root.getJavaProject(); 645 String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true); 646 String 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(); 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 681 public String getClassUnderTestText() { 682 return fClassUnderTestText; 683 } 684 685 690 public IType getClassUnderTest() { 691 return fClassUnderTest; 692 } 693 694 699 public void setClassUnderTest(String name) { 700 if (fClassUnderTestControl != null && !fClassUnderTestControl.isDisposed()) { 701 fClassUnderTestControl.setText(name); 702 } 703 internalSetClassUnderText(name); 704 } 705 706 private void internalSetClassUnderText(String name) { 707 fClassUnderTestText= name; 708 fClassUnderTestStatus= classUnderTestChanged(); 709 handleFieldChanged(CLASS_UNDER_TEST); 710 } 711 712 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); } 742 743 } 744 745 private void createConstructor(IType type, ImportsManager imports) throws CoreException { 746 ITypeHierarchy typeHierarchy= null; 747 IType[] superTypes= null; 748 String 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 [] {"Ljava.lang.String;"}); 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 delimiter= getLineDelimiter(); 772 StringBuffer buffer= new StringBuffer (32); 773 buffer.append("public "); buffer.append(getTypeName()); 775 buffer.append('('); 776 if (!isJUnit4()) { 777 buffer.append(imports.addImport("java.lang.String")).append(" name"); } 779 buffer.append(") {"); buffer.append(delimiter); 781 if (!isJUnit4()) { 782 buffer.append("super(name);").append(delimiter); } 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 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 [] {}); 800 if (testMethod.exists()) { 801 return testMethod; 802 } 803 } 804 } 805 } 806 return null; 807 } 808 809 private void createSetupStubs(IType type, String methodName, boolean isStatic, String annotationType, ImportsManager imports) throws CoreException { 810 String content= null; 811 IMethod methodTemplate= findInHierarchy(type, methodName); 812 String 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 delimiter= getLineDelimiter(); 826 StringBuffer buffer= new StringBuffer (); 827 if (settings.createComments) { 828 String [] excSignature= { Signature.createTypeSignature("java.lang.Exception", true) }; String comment= CodeGeneration.getMethodComment(type.getCompilationUnit(), type.getElementName(), methodName, new String [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 "); } else { 841 buffer.append("protected "); } 843 if (isStatic) { 844 buffer.append("static "); } 846 buffer.append("void "); buffer.append(methodName); 848 buffer.append("() throws "); buffer.append(imports.addImport("java.lang.Exception")); buffer.append(" {}"); 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); } 862 863 private void createTearDown(IType type, ImportsManager imports) throws CoreException { 864 createSetupStubs(type, "tearDown", false, "org.junit.After", imports); } 866 867 private void createSetUpClass(IType type, ImportsManager imports) throws CoreException { 868 createSetupStubs(type, "setUpBeforeClass", true, "org.junit.BeforeClass", imports); } 870 871 private void createTearDownClass(IType type, ImportsManager imports) throws CoreException { 872 createSetupStubs(type, "tearDownAfterClass", true, "org.junit.AfterClass", imports); } 874 875 private void createTestMethodStubs(IType type, ImportsManager imports) throws CoreException { 876 IMethod[] methods= fPage2.getCheckedMethods(); 877 if (methods.length == 0) 878 return; 879 880 IMethod[] allMethodsArray= fPage2.getAllMethods(); 881 List allMethods= new ArrayList (); 882 allMethods.addAll(Arrays.asList(allMethodsArray)); 883 List overloadedMethods= getOverloadedMethods(allMethods); 884 885 889 List names= new ArrayList (); 890 for (int i = 0; i < methods.length; i++) { 891 IMethod method= methods[i]; 892 String elementName= method.getElementName(); 893 StringBuffer name= new StringBuffer (PREFIX).append(Character.toUpperCase(elementName.charAt(0))).append(elementName.substring(1)); 894 StringBuffer buffer= new StringBuffer (); 895 896 final boolean contains= overloadedMethods.contains(method); 897 if (contains) 898 appendParameterNamesToMethodName(name, method.getParameterTypes()); 899 900 replaceIllegalCharacters(name); 901 909 String 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 "); if (fPage2.getCreateFinalMethodStubsButtonSelection()) 928 buffer.append("final "); buffer.append("void "); buffer.append(testName); 931 buffer.append("()"); appendTestMethodBody(buffer, testName, method, type.getCompilationUnit(), imports); 933 type.createMethod(buffer.toString(), null, false, null); 934 } 935 } 936 937 private void replaceIllegalCharacters(StringBuffer 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 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 buffer, String name, IMethod method, ICompilationUnit targetCu, ImportsManager imports) throws CoreException { 962 final String delimiter= getLineDelimiter(); 963 buffer.append('{').append(delimiter); 964 String todoTask= ""; if (fPage2.isCreateTasks()) { 966 String todoTaskTag= JUnitStubUtility.getTodoTaskTag(targetCu.getJavaProject()); 967 if (todoTaskTag != null) { 968 todoTask= " // " + todoTaskTag; } 970 } 971 String message= WizardMessages.NewTestCaseWizardPageOne_not_yet_implemented_string; 972 buffer.append(Messages.format("fail(\"{0}\");", message)).append(todoTask).append(delimiter); 974 buffer.append('}').append(delimiter); 975 } 976 977 private void appendParameterNamesToMethodName(StringBuffer buffer, String [] parameters) { 978 for (int i= 0; i < parameters.length; i++) { 979 final StringBuffer buf= new StringBuffer (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"); } 987 } 988 } 989 990 private void appendMethodComment(StringBuffer buffer, IMethod method) throws JavaModelException { 991 final String delimiter= getLineDelimiter(); 992 final StringBuffer buf= new StringBuffer ("{@link "); JavaElementLabels.getTypeLabel(method.getDeclaringType(), JavaElementLabels.T_FULLY_QUALIFIED, buf); 994 buf.append('#'); 995 buf.append(method.getElementName()); 996 buf.append('('); 997 String [] paramTypes= JUnitStubUtility.getParameterTypeNamesForSeeTag(method); 998 for (int i= 0; i < paramTypes.length; i++) { 999 if (i != 0) { 1000 buf.append(", "); } 1002 buf.append(paramTypes[i]); 1003 1004 } 1005 buf.append(')'); 1006 buf.append('}'); 1007 1008 buffer.append("/**"); buffer.append(delimiter); 1010 buffer.append(" * "); buffer.append(Messages.format(WizardMessages.NewTestCaseWizardPageOne_comment_class_to_test, buf.toString())); 1012 buffer.append(delimiter); 1013 buffer.append(" */"); buffer.append(delimiter); 1015 } 1016 1017 1018 private List getOverloadedMethods(List allMethods) { 1019 List overloadedMethods= new ArrayList (); 1020 for (int i= 0; i < allMethods.size(); i++) { 1021 IMethod current= (IMethod) allMethods.get(i); 1022 String currentName= current.getElementName(); 1023 boolean currentAdded= false; 1024 for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { 1025 IMethod iterMethod= (IMethod) iter.next(); 1026 if (iterMethod.getElementName().equals(currentName)) { 1027 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 1043 public void setVisible(boolean visible) { 1044 super.setVisible(visible); 1045 if (!visible) { 1046 saveWidgetValues(); 1047 } 1048 1049 } 1051 1052 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 1090 protected IStatus superClassChanged() { 1091 if (isJUnit4()) { 1093 return new JUnitStatus(); 1094 } 1095 1096 String superClassName= getSuperClass(); 1097 JUnitStatus status= new JUnitStatus(); 1098 if (superClassName == null || superClassName.trim().equals("")) { 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)) { 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 1127 public boolean canFlipToNextPage() { 1128 return super.canFlipToNextPage() && getClassUnderTest() != null; 1129 } 1130 1131 private IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { 1132 if (!jproject.exists()) { 1133 return null; 1134 } 1135 1136 IType type= jproject.findType(classToTestName); 1137 1138 if (type == null && pack != null && !pack.isDefaultPackage()) { 1140 type= jproject.findType(pack.getElementName(), classToTestName); 1141 } 1142 1143 if (type == null) { 1145 type= jproject.findType("java.lang", classToTestName); } 1147 return type; 1148 } 1149 1150 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); fMethodStubsButtons.setSelection(IDX_TEARDOWN, false); fMethodStubsButtons.setSelection(IDX_SETUP_CLASS, false); fMethodStubsButtons.setSelection(IDX_TEARDOWN_CLASS, false); fMethodStubsButtons.setSelection(IDX_CONSTRUCTOR, false); } 1169 } 1170 1171 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 |