1 12 package org.eclipse.jdt.internal.junit.wizards; 13 14 import java.lang.reflect.InvocationTargetException ; 15 import java.util.ArrayList ; 16 import java.util.Arrays ; 17 import java.util.List ; 18 import java.util.ListIterator ; 19 20 import org.eclipse.core.runtime.CoreException; 21 import org.eclipse.core.runtime.IPath; 22 import org.eclipse.core.runtime.IProgressMonitor; 23 import org.eclipse.core.runtime.IStatus; 24 import org.eclipse.core.runtime.Path; 25 26 import org.eclipse.core.resources.IProject; 27 import org.eclipse.core.resources.ResourcesPlugin; 28 29 import org.eclipse.jdt.core.Flags; 30 import org.eclipse.jdt.core.IClassFile; 31 import org.eclipse.jdt.core.IClasspathEntry; 32 import org.eclipse.jdt.core.ICompilationUnit; 33 import org.eclipse.jdt.core.IJavaElement; 34 import org.eclipse.jdt.core.IJavaProject; 35 import org.eclipse.jdt.core.IMethod; 36 import org.eclipse.jdt.core.IPackageFragment; 37 import org.eclipse.jdt.core.IPackageFragmentRoot; 38 import org.eclipse.jdt.core.IType; 39 import org.eclipse.jdt.core.ITypeHierarchy; 40 import org.eclipse.jdt.core.JavaConventions; 41 import org.eclipse.jdt.core.JavaCore; 42 import org.eclipse.jdt.core.JavaModelException; 43 import org.eclipse.jdt.core.Signature; 44 import org.eclipse.jdt.core.search.IJavaSearchScope; 45 import org.eclipse.jdt.core.search.SearchEngine; 46 import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; 47 import org.eclipse.jdt.internal.corext.util.JavaModelUtil; 48 import org.eclipse.jdt.internal.junit.ui.IJUnitHelpContextIds; 49 import org.eclipse.jdt.internal.junit.ui.JUnitPlugin; 50 import org.eclipse.jdt.internal.junit.util.JUnitStatus; 51 import org.eclipse.jdt.internal.junit.util.JUnitStubUtility; 52 import org.eclipse.jdt.internal.junit.util.LayoutUtil; 53 import org.eclipse.jdt.internal.junit.util.TestSearchEngine; 54 import org.eclipse.jdt.internal.junit.util.JUnitStubUtility.GenStubSettings; 55 import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; 56 import org.eclipse.jdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper; 57 import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor; 58 import org.eclipse.jdt.internal.ui.util.SWTUtil; 59 import org.eclipse.jdt.ui.IJavaElementSearchConstants; 60 import org.eclipse.jdt.ui.JavaUI; 61 import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; 62 import org.eclipse.jface.dialogs.Dialog; 63 import org.eclipse.jface.dialogs.ErrorDialog; 64 import org.eclipse.jface.dialogs.IDialogSettings; 65 import org.eclipse.jface.dialogs.MessageDialog; 66 import org.eclipse.jface.operation.IRunnableWithProgress; 67 import org.eclipse.jface.viewers.IStructuredSelection; 68 import org.eclipse.jface.window.Window; 69 import org.eclipse.swt.SWT; 70 import org.eclipse.swt.events.ModifyEvent; 71 import org.eclipse.swt.events.ModifyListener; 72 import org.eclipse.swt.events.SelectionEvent; 73 import org.eclipse.swt.events.SelectionListener; 74 import org.eclipse.swt.layout.GridData; 75 import org.eclipse.swt.layout.GridLayout; 76 import org.eclipse.swt.widgets.Button; 77 import org.eclipse.swt.widgets.Composite; 78 import org.eclipse.swt.widgets.Label; 79 import org.eclipse.swt.widgets.Shell; 80 import org.eclipse.swt.widgets.Text; 81 import org.eclipse.ui.PlatformUI; 82 import org.eclipse.ui.dialogs.SelectionDialog; 83 import org.eclipse.ui.help.WorkbenchHelp; 84 85 88 public class NewTestCaseCreationWizardPage extends NewTypeWizardPage implements IAboutToRunOperation { 89 90 private final static String PAGE_NAME= "NewTestCaseCreationWizardPage"; private final static String CLASS_TO_TEST= PAGE_NAME + ".classtotest"; private final static String TEST_SUFFIX= "Test"; private final static String SETUP= "setUp"; private final static String TEARDOWN= "tearDown"; 96 private final static String STORE_GENERATE_MAIN= PAGE_NAME + ".GENERATE_MAIN"; private final static String STORE_USE_TESTRUNNER= PAGE_NAME + ".USE_TESTRUNNER"; private final static String STORE_TESTRUNNER_TYPE= PAGE_NAME + ".TESTRUNNER_TYPE"; 100 private String fDefaultClassToTest; 101 private NewTestCaseCreationWizardPage2 fPage2; 102 private MethodStubsSelectionButtonGroup fMethodStubsButtons; 103 104 private IType fClassToTest; 105 private IStatus fClassToTestStatus; 106 private IStatus fTestClassStatus; 107 108 private int fIndexOfFirstTestMethod; 109 110 private Label fClassToTestLabel; 111 private Text fClassToTestText; 112 private Button fClassToTestButton; 113 private JavaTypeCompletionProcessor fClassToTestCompletionProcessor; 114 115 private boolean fFirstTime; 116 private String fMainMethod; 117 118 public NewTestCaseCreationWizardPage() { 119 super(true, PAGE_NAME); 120 fFirstTime= true; 121 122 setTitle(WizardMessages.getString("NewTestClassWizPage.title")); setDescription(WizardMessages.getString("NewTestClassWizPage.description")); 125 String [] buttonNames= new String [] { 126 "public static void main(Strin&g[] args)", 128 WizardMessages.getString("NewTestClassWizPage.methodStub.testRunner"), WizardMessages.getString("NewTestClassWizPage.methodStub.setUp"), WizardMessages.getString("NewTestClassWizPage.methodStub.tearDown"), WizardMessages.getString("NewTestClassWizPage.methodStub.constructor") }; 133 134 fMethodStubsButtons= new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 1); 135 fMethodStubsButtons.setLabelText(WizardMessages.getString("NewTestClassWizPage.method.Stub.label")); 137 fClassToTestCompletionProcessor= new JavaTypeCompletionProcessor(false, false); 139 fClassToTestStatus= new JUnitStatus(); 140 fTestClassStatus= new JUnitStatus(); 141 142 fDefaultClassToTest= ""; } 144 145 148 public void init(IStructuredSelection selection, NewTestCaseCreationWizardPage2 page2) { 149 fPage2= page2; 150 IJavaElement element= getInitialJavaElement(selection); 151 152 initContainerPage(element); 153 initTypePage(element); 154 doStatusUpdate(); 155 if (element != null) { 157 IType classToTest= null; 158 IType typeInCompUnit= (IType) element.getAncestor(IJavaElement.TYPE); 160 if (typeInCompUnit != null) { 161 if (typeInCompUnit.getCompilationUnit() != null) { 162 classToTest= typeInCompUnit; 163 } 164 } else { 165 ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); 166 if (cu != null) 167 classToTest= cu.findPrimaryType(); 168 else { 169 if (element instanceof IClassFile) { 170 try { 171 IClassFile cf= (IClassFile) element; 172 if (cf.isStructureKnown()) 173 classToTest= cf.getType(); 174 } catch(JavaModelException e) { 175 JUnitPlugin.log(e); 176 } 177 } 178 } 179 } 180 if (classToTest != null) { 181 try { 182 if (!TestSearchEngine.isTestImplementor(classToTest)) { 183 fDefaultClassToTest= classToTest.getFullyQualifiedName(); 184 } 185 } catch (JavaModelException e) { 186 JUnitPlugin.log(e); 187 } 188 } 189 } 190 fMethodStubsButtons.setSelection(0, false); fMethodStubsButtons.setSelection(1, false); fMethodStubsButtons.setEnabled(1, false); fMethodStubsButtons.setSelection(2, false); fMethodStubsButtons.setSelection(3, false); fMethodStubsButtons.setSelection(4, false); } 197 198 201 protected void handleFieldChanged(String fieldName) { 202 super.handleFieldChanged(fieldName); 203 if (fieldName.equals(CLASS_TO_TEST)) { 204 fClassToTestStatus= classToTestClassChanged(); 205 } else if (fieldName.equals(SUPER)) { 206 validateSuperClass(); 207 if (!fFirstTime) 208 fTestClassStatus= typeNameChanged(); 209 } else if (fieldName.equals(TYPENAME)) { 210 fTestClassStatus= typeNameChanged(); 211 } else if (fieldName.equals(PACKAGE) || fieldName.equals(CONTAINER) || fieldName.equals(SUPER)) { 212 if (fieldName.equals(PACKAGE)) 213 fPackageStatus= packageChanged(); 214 if (!fFirstTime) { 215 validateSuperClass(); 216 fClassToTestStatus= classToTestClassChanged(); 217 fTestClassStatus= typeNameChanged(); 218 } 219 if (fieldName.equals(CONTAINER)) { 220 validateJUnitOnBuildPath(); 221 } 222 } 223 doStatusUpdate(); 224 } 225 226 private void doStatusUpdate() { 228 IStatus[] status= new IStatus[] { 230 fContainerStatus, 231 fPackageStatus, 232 fTestClassStatus, 233 fClassToTestStatus, 234 fModifierStatus, 235 fSuperClassStatus 236 }; 237 238 updateStatus(status); 240 } 241 242 245 public void createControl(Composite parent) { 246 initializeDialogUnits(parent); 247 248 Composite composite= new Composite(parent, SWT.NONE); 249 250 int nColumns= 4; 251 252 GridLayout layout= new GridLayout(); 253 layout.numColumns= nColumns; 254 composite.setLayout(layout); 255 256 createContainerControls(composite, nColumns); 257 createPackageControls(composite, nColumns); 258 createSeparator(composite, nColumns); 259 createTypeNameControls(composite, nColumns); 260 createSuperClassControls(composite, nColumns); 261 createMethodStubSelectionControls(composite, nColumns); 262 setSuperClass(JUnitPlugin.TEST_SUPERCLASS_NAME, true); 263 createSeparator(composite, nColumns); 264 createClassToTestControls(composite, nColumns); 265 266 setControl(composite); 267 268 if (fDefaultClassToTest.length() > 0) { 270 fClassToTestText.setText(fDefaultClassToTest); 271 setTypeName(Signature.getSimpleName(fDefaultClassToTest)+TEST_SUFFIX, true); 272 } 273 restoreWidgetValues(); 274 Dialog.applyDialogFont(composite); 275 WorkbenchHelp.setHelp(composite, IJUnitHelpContextIds.NEW_TESTCASE_WIZARD_PAGE); 276 277 } 278 279 private void createMethodStubSelectionControls(Composite composite, int nColumns) { 280 LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns); 281 LayoutUtil.createEmptySpace(composite,1); 282 LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1); 283 } 284 285 private void createClassToTestControls(Composite composite, int nColumns) { 286 fClassToTestLabel= new Label(composite, SWT.LEFT | SWT.WRAP); 287 fClassToTestLabel.setFont(composite.getFont()); 288 289 fClassToTestLabel.setText(WizardMessages.getString("NewTestClassWizPage.class_to_test.label")); GridData gd= new GridData(); 291 gd.horizontalSpan= 1; 292 fClassToTestLabel.setLayoutData(gd); 293 294 fClassToTestText= new Text(composite, SWT.SINGLE | SWT.BORDER); 295 fClassToTestText.setEnabled(true); 296 fClassToTestText.setFont(composite.getFont()); 297 fClassToTestText.addModifyListener(new ModifyListener() { 298 public void modifyText(ModifyEvent e) { 299 handleFieldChanged(CLASS_TO_TEST); 300 } 301 }); 302 gd= new GridData(); 303 gd.horizontalAlignment= GridData.FILL; 304 gd.grabExcessHorizontalSpace= true; 305 gd.horizontalSpan= nColumns - 2; 306 fClassToTestText.setLayoutData(gd); 307 308 fClassToTestButton= new Button(composite, SWT.PUSH); 309 fClassToTestButton.setText(WizardMessages.getString("NewTestClassWizPage.class_to_test.browse")); fClassToTestButton.setEnabled(true); 311 fClassToTestButton.addSelectionListener(new SelectionListener() { 312 public void widgetDefaultSelected(SelectionEvent e) { 313 classToTestButtonPressed(); 314 } 315 public void widgetSelected(SelectionEvent e) { 316 classToTestButtonPressed(); 317 } 318 }); 319 gd= new GridData(); 320 gd.horizontalAlignment= GridData.FILL; 321 gd.grabExcessHorizontalSpace= false; 322 gd.horizontalSpan= 1; 323 gd.heightHint = SWTUtil.getButtonHeightHint(fClassToTestButton); 324 gd.widthHint = SWTUtil.getButtonWidthHint(fClassToTestButton); 325 fClassToTestButton.setLayoutData(gd); 326 327 ControlContentAssistHelper.createTextContentAssistant(fClassToTestText, fClassToTestCompletionProcessor); 328 } 329 330 private void classToTestButtonPressed() { 331 IType type= chooseClassToTestType(); 332 if (type != null) { 333 fClassToTestText.setText(JavaModelUtil.getFullyQualifiedName(type)); 334 handleFieldChanged(CLASS_TO_TEST); 335 } 336 } 337 338 private IType chooseClassToTestType() { 339 IPackageFragmentRoot root= getPackageFragmentRoot(); 340 if (root == null) 341 return null; 342 343 IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; 344 IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); 345 346 IType type= null; 347 try { 348 SelectionDialog dialog= JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, getClassToTestText()); 349 dialog.setTitle(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.title")); dialog.setMessage(WizardMessages.getString("NewTestClassWizPage.class_to_test.dialog.message")); dialog.open(); 352 if (dialog.getReturnCode() != Window.OK) 353 return type; 354 else { 355 Object [] resultArray= dialog.getResult(); 356 if (resultArray != null && resultArray.length > 0) 357 type= (IType) resultArray[0]; 358 } 359 } catch (JavaModelException e) { 360 JUnitPlugin.log(e); 361 } 362 return type; 363 } 364 365 368 protected IStatus packageChanged() { 369 IStatus status= super.packageChanged(); 370 fClassToTestCompletionProcessor.setPackageFragment(getPackageFragment()); 371 return status; 372 } 373 374 private IStatus classToTestClassChanged() { 375 fClassToTestButton.setEnabled(getPackageFragmentRoot() != null); IStatus status= validateClassToTest(); 377 return status; 378 } 379 380 383 public String getClassToTestText() { 384 return fClassToTestText.getText(); 385 } 386 387 390 public IType getClassToTest() { 391 return fClassToTest; 392 } 393 394 397 public void setClassToTest(String name) { 398 fClassToTestText.setText(name); 399 } 400 401 404 protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException { 405 fIndexOfFirstTestMethod= 0; 406 407 if (fMethodStubsButtons.isSelected(0)) 408 createMain(type); 409 410 if (fMethodStubsButtons.isSelected(2)) { 411 createSetUp(type, imports); 412 } 413 414 if (fMethodStubsButtons.isSelected(3)) { 415 createTearDown(type, imports); 416 } 417 418 if (fMethodStubsButtons.isSelected(4)) 419 createConstructor(type, imports); 420 421 if (fClassToTest != null) { 422 createTestMethodStubs(type); 423 } 424 } 425 426 private void createConstructor(IType type, ImportsManager imports) throws JavaModelException { 427 ITypeHierarchy typeHierarchy= null; 428 IType[] superTypes= null; 429 String constr= ""; IMethod methodTemplate= null; 431 if (type.exists()) { 432 typeHierarchy= type.newSupertypeHierarchy(null); 433 superTypes= typeHierarchy.getAllSuperclasses(type); 434 for (int i= 0; i < superTypes.length; i++) { 435 if (superTypes[i].exists()) { 436 IMethod constrMethod= superTypes[i].getMethod(superTypes[i].getElementName(), new String [] {"Ljava.lang.String;"}); if (constrMethod.exists() && constrMethod.isConstructor()) { 438 methodTemplate= constrMethod; 439 break; 440 } 441 } 442 } 443 } 444 CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); 445 if (methodTemplate != null) { 446 GenStubSettings genStubSettings= new GenStubSettings(settings); 447 genStubSettings.fCallSuper= true; 448 genStubSettings.fMethodOverwrites= true; 449 constr= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); 450 } else { 451 constr += "public "+getTypeName()+"(String name) {" + getLineDelimiter() + 453 "super(name);" + getLineDelimiter() + 455 "}" + getLineDelimiter() + getLineDelimiter(); 457 } 458 type.createMethod(constr, null, true, null); 459 fIndexOfFirstTestMethod++; 460 } 461 462 private void createMain(IType type) throws JavaModelException { 463 type.createMethod(fMainMethod, null, false, null); 464 fIndexOfFirstTestMethod++; 465 } 466 467 private void createSetUp(IType type, ImportsManager imports) throws JavaModelException { 468 ITypeHierarchy typeHierarchy= null; 469 IType[] superTypes= null; 470 String setUp= ""; IMethod methodTemplate= null; 472 if (type.exists()) { 473 typeHierarchy= type.newSupertypeHierarchy(null); 474 superTypes= typeHierarchy.getAllSuperclasses(type); 475 for (int i= 0; i < superTypes.length; i++) { 476 if (superTypes[i].exists()) { 477 IMethod testMethod= superTypes[i].getMethod(SETUP, new String [] {}); 478 if (testMethod.exists()) { 479 methodTemplate= testMethod; 480 break; 481 } 482 } 483 } 484 } 485 CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); 486 if (methodTemplate != null) { 487 GenStubSettings genStubSettings= new GenStubSettings(settings); 488 genStubSettings.fCallSuper= true; 489 genStubSettings.fMethodOverwrites= true; 490 setUp= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); 491 } else { 492 if (settings.createComments) 493 setUp= "/**" + getLineDelimiter() + 495 " * Sets up the fixture, for example, open a network connection." + getLineDelimiter() + 497 " * This method is called before a test is executed." + getLineDelimiter() + 499 " * @throws Exception" + getLineDelimiter() + 501 " */" + getLineDelimiter(); 503 setUp+= "protected void "+SETUP+"() throws Exception {}" + getLineDelimiter() + getLineDelimiter(); 505 } 506 type.createMethod(setUp, null, false, null); 507 fIndexOfFirstTestMethod++; 508 } 509 510 private void createTearDown(IType type, ImportsManager imports) throws JavaModelException { 511 ITypeHierarchy typeHierarchy= null; 512 IType[] superTypes= null; 513 String tearDown= ""; IMethod methodTemplate= null; 515 if (type.exists()) { 516 if (typeHierarchy == null) { 517 typeHierarchy= type.newSupertypeHierarchy(null); 518 superTypes= typeHierarchy.getAllSuperclasses(type); 519 } 520 for (int i= 0; i < superTypes.length; i++) { 521 if (superTypes[i].exists()) { 522 IMethod testM= superTypes[i].getMethod(TEARDOWN, new String [] {}); 523 if (testM.exists()) { 524 methodTemplate= testM; 525 break; 526 } 527 } 528 } 529 } 530 CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); 531 if (methodTemplate != null) { 532 GenStubSettings genStubSettings= new GenStubSettings(settings); 533 genStubSettings.fCallSuper= true; 534 genStubSettings.fMethodOverwrites= true; 535 tearDown= JUnitStubUtility.genStub(getTypeName(), methodTemplate, genStubSettings, imports); 536 type.createMethod(tearDown, null, false, null); 537 fIndexOfFirstTestMethod++; 538 } 539 } 540 541 private void createTestMethodStubs(IType type) throws JavaModelException { 542 IMethod[] methods= fPage2.getCheckedMethods(); 543 if (methods.length == 0) 544 return; 545 546 IMethod[] allMethodsArray= fPage2.getAllMethods(); 547 List allMethods= new ArrayList (); 548 allMethods.addAll(Arrays.asList(allMethodsArray)); 549 List overloadedMethods= getOveloadedMethods(allMethods); 550 551 555 List newMethodsNames= new ArrayList (); 556 for (int i = 0; i < methods.length; i++) { 557 IMethod testedMethod= methods[i]; 558 String elementName= testedMethod.getElementName(); 559 StringBuffer methodName= new StringBuffer (NewTestCaseCreationWizardPage2.PREFIX+Character.toUpperCase(elementName.charAt(0))+elementName.substring(1)); 560 StringBuffer newMethod= new StringBuffer (); 561 562 if (overloadedMethods.contains(testedMethod)) { 563 appendMethodComment(newMethod, testedMethod); 564 String [] params= testedMethod.getParameterTypes(); 565 appendParameterNamesToMethodName(methodName, params); 566 } 567 576 if (newMethodsNames.contains(methodName.toString())) { 577 int suffix= 1; 578 while (newMethodsNames.contains(methodName.toString() + Integer.toString(suffix))) 579 suffix++; 580 methodName.append(Integer.toString(suffix)); 581 } 582 newMethodsNames.add(methodName.toString()); 583 newMethod.append("public "); if (fPage2.getCreateFinalMethodStubsButtonSelection()) 585 newMethod.append("final "); newMethod.append("void "); newMethod.append(methodName.toString()); 588 newMethod.append("()"); appendTestMethodBody(newMethod, testedMethod); 590 type.createMethod(newMethod.toString(), null, false, null); 591 } 592 } 593 594 private String getLineDelimiter(){ 595 IType classToTest= getClassToTest(); 596 597 if (classToTest != null && classToTest.exists()) 598 return JUnitStubUtility.getLineDelimiterUsed(classToTest); 599 else 600 return JUnitStubUtility.getLineDelimiterUsed(getPackageFragment()); 601 } 602 603 private void appendTestMethodBody(StringBuffer newMethod, IMethod testedMethod) { 604 newMethod.append("{"); if (createTasks()){ 606 newMethod.append(getLineDelimiter()); 607 newMethod.append("//"); newMethod.append(JUnitStubUtility.getTodoTaskTag(getPackageFragment().getJavaProject())); 609 newMethod.append(WizardMessages.getFormattedString("NewTestClassWizPage.marker.message", testedMethod.getElementName())); newMethod.append(getLineDelimiter()); 611 } 612 newMethod.append("}").append(getLineDelimiter()).append(getLineDelimiter()); } 614 615 public void appendParameterNamesToMethodName(StringBuffer methodName, String [] params) { 616 for (int i= 0; i < params.length; i++) { 617 String param= params[i]; 618 methodName.append(Signature.getSimpleName(Signature.toString(Signature.getElementType(param)))); 619 for (int j= 0, arrayCount= Signature.getArrayCount(param); j < arrayCount; j++) { 620 methodName.append("Array"); } 622 } 623 } 624 625 private void appendMethodComment(StringBuffer newMethod, IMethod method) throws JavaModelException { 626 String returnType= Signature.toString(method.getReturnType()); 627 String body= WizardMessages.getFormattedString("NewTestClassWizPage.comment.class_to_test", new String []{returnType, method.getElementName()}); newMethod.append("/*"); newMethod.append(getLineDelimiter()); 630 newMethod.append(" * "); newMethod.append(body); 632 newMethod.append("("); String [] paramTypes= method.getParameterTypes(); 634 if (paramTypes.length > 0) { 635 if (paramTypes.length > 1) { 636 for (int j= 0; j < paramTypes.length-1; j++) { 637 newMethod.append(Signature.toString(paramTypes[j])+", "); } 639 } 640 newMethod.append(Signature.toString(paramTypes[paramTypes.length-1])); 641 } 642 newMethod.append(")"); newMethod.append(getLineDelimiter()); 644 newMethod.append(" */"); newMethod.append(getLineDelimiter()); 646 } 647 648 private List getOveloadedMethods(List allMethods) { 649 List overloadedMethods= new ArrayList (); 650 for (int i= 0; i < allMethods.size(); i++) { 651 IMethod current= (IMethod) allMethods.get(i); 652 String currentName= current.getElementName(); 653 boolean currentAdded= false; 654 for (ListIterator iter= allMethods.listIterator(i+1); iter.hasNext(); ) { 655 IMethod iterMethod= (IMethod) iter.next(); 656 if (iterMethod.getElementName().equals(currentName)) { 657 if (!currentAdded) { 659 overloadedMethods.add(current); 660 currentAdded= true; 661 } 662 overloadedMethods.add(iterMethod); 663 iter.remove(); 664 } 665 } 666 } 667 return overloadedMethods; 668 } 669 670 673 public void setVisible(boolean visible) { 674 super.setVisible(visible); 675 676 if (visible && fFirstTime) { 677 if (getClassToTestText().equals("")) setPageComplete(false); 679 else 680 handleFieldChanged(CLASS_TO_TEST); fFirstTime= false; 682 } 683 684 if (visible) setFocus(); 685 } 686 687 private void validateJUnitOnBuildPath() { 688 IPackageFragmentRoot root= getPackageFragmentRoot(); 689 if (root == null) 690 return; 691 IJavaProject jp= root.getJavaProject(); 692 693 try { 694 if (jp.findType(JUnitPlugin.TEST_SUPERCLASS_NAME) != null) 695 return; 696 } catch (JavaModelException e) { 697 } 698 if (MessageDialog.openQuestion(getShell(), WizardMessages.getString("NewTestClassWizPage.not_on_buildpath.title"), WizardMessages.getString("NewTestClassWizPage.not_on_buildpath.message"))) { try { 700 addJUnitToBuildPath(getShell(), jp); 701 return; 702 } catch(JavaModelException e) { 703 ErrorDialog.openError(getShell(), WizardMessages.getString("NewTestClassWizPage.cannot_add.title"), WizardMessages.getString("NewTestClassWizPage.cannot_add.message"), e.getStatus()); } 705 } 706 JUnitStatus status= new JUnitStatus(); 707 status.setWarning(WizardMessages.getString("NewTestClassWizPage.error.junitNotOnbuildpath")); fContainerStatus= status; 709 } 710 711 public static void addJUnitToBuildPath(Shell shell, IJavaProject project) throws JavaModelException { 712 IProject junitProject= ResourcesPlugin.getWorkspace().getRoot().getProject("org.junit"); IClasspathEntry entry; 714 if (junitProject.exists()) { 715 entry= JavaCore.newProjectEntry(junitProject.getFullPath()); 716 } else { 717 IPath junitHome= new Path(JUnitPlugin.JUNIT_HOME); 718 IPath sourceHome= new Path("ECLIPSE_HOME"); entry= JavaCore.newVariableEntry( 720 junitHome.append("junit.jar"), sourceHome.append("plugins/org.eclipse.jdt.source_3.0.0/src/org.junit_3.8.1/junitsrc.zip"), null 724 ); 725 } 726 addToClasspath(shell, project, entry); 727 } 728 729 private static void addToClasspath(Shell shell, final IJavaProject project, IClasspathEntry entry) throws JavaModelException { 730 IClasspathEntry[] oldEntries= project.getRawClasspath(); 731 for (int i= 0; i < oldEntries.length; i++) { 732 if (oldEntries[i].equals(entry)) { 733 return; 734 } 735 } 736 int nEntries= oldEntries.length; 737 final IClasspathEntry[] newEntries= new IClasspathEntry[nEntries + 1]; 738 System.arraycopy(oldEntries, 0, newEntries, 0, nEntries); 739 newEntries[nEntries]= entry; 740 try { 742 PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() { 743 public void run(IProgressMonitor monitor) throws InvocationTargetException , InterruptedException { 744 try { 745 project.setRawClasspath(newEntries, monitor); 746 } catch (JavaModelException e) { 747 throw new InvocationTargetException (e); 748 } 749 } 750 }); 751 } catch (InvocationTargetException e) { 752 Throwable t = e.getTargetException(); 753 if (t instanceof CoreException) { 754 ErrorDialog.openError(shell, WizardMessages.getString("NewTestClassWizPage.cannot_add.title"), WizardMessages.getString("NewTestClassWizPage.cannot_add.message"), ((CoreException)t).getStatus()); } 756 } catch (InterruptedException e) { 757 return; 758 } 759 } 760 761 762 767 public int getIndexOfFirstMethod() { 768 return fIndexOfFirstTestMethod; 769 } 770 771 private boolean createTasks() { 772 return fPage2.getCreateTasksButtonSelection(); 773 } 774 775 private void validateSuperClass() { 776 fMethodStubsButtons.setEnabled(2, true); fMethodStubsButtons.setEnabled(3, true); String superClassName= getSuperClass(); 779 if (superClassName == null || superClassName.trim().equals("")) { fSuperClassStatus= new JUnitStatus(); 781 ((JUnitStatus)fSuperClassStatus).setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.empty")); return; 783 } 784 if (getPackageFragmentRoot() != null) { try { 786 IType type= resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName); 787 JUnitStatus status = new JUnitStatus(); 788 if (type == null) { 789 790 status.setWarning(WizardMessages.getString("NewTestClassWizPage.error.superclass.not_exist")); fSuperClassStatus= status; 792 } else { 793 if (type.isInterface()) { 794 status.setError(WizardMessages.getString("NewTestClassWizPage.error.superclass.is_interface")); fSuperClassStatus= status; 796 } 797 if (!TestSearchEngine.isTestImplementor(type)) { 798 status.setError(WizardMessages.getFormattedString("NewTestClassWizPage.error.superclass.not_implementing_test_interface", JUnitPlugin.TEST_INTERFACE_NAME)); fSuperClassStatus= status; 800 } else { 801 IMethod setupMethod= type.getMethod(SETUP, new String [] {}); 802 IMethod teardownMethod= type.getMethod(TEARDOWN, new String [] {}); 803 if (setupMethod.exists()) 804 fMethodStubsButtons.setEnabled(2, !Flags.isFinal(setupMethod.getFlags())); 805 if (teardownMethod.exists()) 806 fMethodStubsButtons.setEnabled(3, !Flags.isFinal(teardownMethod.getFlags())); 807 } 808 } 809 } catch (JavaModelException e) { 810 JUnitPlugin.log(e); 811 } 812 } 813 } 814 815 818 public boolean canFlipToNextPage() { 819 return isPageComplete() && getNextPage() != null && isNextPageValid(); 820 } 821 822 protected boolean isNextPageValid() { 823 return !getClassToTestText().equals(""); } 825 826 private JUnitStatus validateClassToTest() { 827 IPackageFragmentRoot root= getPackageFragmentRoot(); 828 IPackageFragment pack= getPackageFragment(); 829 String classToTestName= getClassToTestText(); 830 JUnitStatus status= new JUnitStatus(); 831 832 fClassToTest= null; 833 if (classToTestName.length() == 0) { 834 return status; 835 } 836 IStatus val= JavaConventions.validateJavaTypeName(classToTestName); 837 if (val.getSeverity() == IStatus.ERROR) { 839 status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); return status; 841 } 842 843 if (root != null) { 844 try { 845 IType type= resolveClassNameToType(root.getJavaProject(), pack, classToTestName); 846 if (type == null) { 847 status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_exist")); return status; 850 } else { 851 if (type.isInterface()) { 852 status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.is_interface",classToTestName)); } 854 if (pack != null && !JavaModelUtil.isVisible(type, pack)) { 855 status.setWarning(WizardMessages.getFormattedString("NewTestClassWizPage.warning.class_to_test.not_visible", new String [] {(type.isInterface())?WizardMessages.getString("Interface"):WizardMessages.getString("Class") , classToTestName})); } 857 } 858 fClassToTest= type; 859 } catch (JavaModelException e) { 860 status.setError(WizardMessages.getString("NewTestClassWizPage.error.class_to_test.not_valid")); } 862 } else { 863 status.setError(""); } 865 return status; 866 } 867 868 private IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException { 869 IType type= null; 870 if (type == null && pack != null) { 871 String packName= pack.getElementName(); 872 if (!pack.isDefaultPackage()) { 874 type= jproject.findType(packName, classToTestName); 875 } 876 if (type == null && !"java.lang".equals(packName)) { type= jproject.findType("java.lang", classToTestName); } 880 } 881 if (type == null) { 883 type= jproject.findType(classToTestName); 884 } 885 return type; 886 } 887 888 892 private void restoreWidgetValues() { 893 894 IDialogSettings settings= getDialogSettings(); 895 if (settings != null) { 896 boolean generateMain= settings.getBoolean(STORE_GENERATE_MAIN); 897 fMethodStubsButtons.setSelection(0, generateMain); 898 fMethodStubsButtons.setEnabled(1, generateMain); 899 fMethodStubsButtons.setSelection(1,settings.getBoolean(STORE_USE_TESTRUNNER)); 900 try { 901 fMethodStubsButtons.setComboSelection(settings.getInt(STORE_TESTRUNNER_TYPE)); 902 } catch(NumberFormatException e) {} 903 } 904 } 905 906 910 void saveWidgetValues() { 911 IDialogSettings settings= getDialogSettings(); 912 if (settings != null) { 913 settings.put(STORE_GENERATE_MAIN, fMethodStubsButtons.isSelected(0)); 914 settings.put(STORE_USE_TESTRUNNER, fMethodStubsButtons.isSelected(1)); 915 settings.put(STORE_TESTRUNNER_TYPE, fMethodStubsButtons.getComboSelection()); 916 } 917 } 918 919 public void aboutToRunOperation() { 920 fMainMethod= fMethodStubsButtons.getMainMethod(getTypeName()); 921 } 922 923 } 924 | Popular Tags |