public Collection<PsiElement> getAdditionalElementsToDelete( @NotNull final PsiElement element, @NotNull final Collection<PsiElement> allElementsToDelete, final boolean askUser) { if (element instanceof PsiField) { PsiField field = (PsiField) element; final Project project = element.getProject(); String propertyName = JavaCodeStyleManager.getInstance(project) .variableNameToPropertyName(field.getName(), VariableKind.FIELD); PsiClass aClass = field.getContainingClass(); if (aClass != null) { boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); PsiMethod[] getters = GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic); if (getters != null) { final List<PsiMethod> validGetters = new ArrayList<>(1); for (PsiMethod getter : getters) { if (!allElementsToDelete.contains(getter) && (getter != null && getter.isPhysical())) { validGetters.add(getter); } } getters = validGetters.isEmpty() ? null : validGetters.toArray(new PsiMethod[validGetters.size()]); } PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false); if (allElementsToDelete.contains(setter) || setter != null && !setter.isPhysical()) setter = null; if (askUser && (getters != null || setter != null)) { final String message = RefactoringMessageUtil.getGetterSetterMessage( field.getName(), RefactoringBundle.message("delete.title"), getters != null ? getters[0] : null, setter); if (!ApplicationManager.getApplication().isUnitTestMode() && Messages.showYesNoDialog( project, message, RefactoringBundle.message("safe.delete.title"), Messages.getQuestionIcon()) != Messages.YES) { getters = null; setter = null; } } List<PsiElement> elements = new ArrayList<>(); if (setter != null) elements.add(setter); if (getters != null) Collections.addAll(elements, getters); return elements; } } return null; }
@Override protected boolean preprocessUsages(@NotNull final Ref<UsageInfo[]> refUsages) { final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>(); myExtractEnumProcessor.findEnumConstantConflicts(refUsages); if (!DestinationFolderComboBox.isAccessible( myProject, sourceClass.getContainingFile().getVirtualFile(), myClass.getContainingFile().getContainingDirectory().getVirtualFile())) { conflicts.putValue( sourceClass, "Extracted class won't be accessible in " + RefactoringUIUtil.getDescription(sourceClass, true)); } ApplicationManager.getApplication() .runWriteAction( new Runnable() { public void run() { myClass.delete(); } }); final Project project = sourceClass.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiClass existingClass = JavaPsiFacade.getInstance(project).findClass(getQualifiedName(), scope); if (existingClass != null) { conflicts.putValue( existingClass, RefactorJBundle.message("cannot.perform.the.refactoring") + RefactorJBundle.message("there.already.exists.a.class.with.the.chosen.name")); } if (!myGenerateAccessors) { calculateInitializersConflicts(conflicts); final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass(); final NecessaryAccessorsVisitor srcVisitor = checkNecessaryGettersSetters4SourceClass(); final Set<PsiField> fieldsNeedingGetter = new LinkedHashSet<PsiField>(); fieldsNeedingGetter.addAll(visitor.getFieldsNeedingGetter()); fieldsNeedingGetter.addAll(srcVisitor.getFieldsNeedingGetter()); for (PsiField field : fieldsNeedingGetter) { conflicts.putValue(field, "Field \'" + field.getName() + "\' needs getter"); } final Set<PsiField> fieldsNeedingSetter = new LinkedHashSet<PsiField>(); fieldsNeedingSetter.addAll(visitor.getFieldsNeedingSetter()); fieldsNeedingSetter.addAll(srcVisitor.getFieldsNeedingSetter()); for (PsiField field : fieldsNeedingSetter) { conflicts.putValue(field, "Field \'" + field.getName() + "\' needs setter"); } } checkConflicts(refUsages, conflicts); return showConflicts(conflicts, refUsages.get()); }
@Nullable static HighlightInfo checkFinalFieldInitialized(@NotNull PsiField field) { if (!field.hasModifierProperty(PsiModifier.FINAL)) return null; if (isFieldInitializedAfterObjectConstruction(field)) return null; String description = JavaErrorMessages.message("variable.not.initialized", field.getName()); TextRange range = HighlightNamesUtil.getFieldDeclarationTextRange(field); HighlightInfo highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR) .range(range) .descriptionAndTooltip(description) .create(); QuickFixAction.registerQuickFixAction( highlightInfo, HighlightMethodUtil.getFixRange(field), QUICK_FIX_FACTORY.createCreateConstructorParameterFromFieldFix(field)); QuickFixAction.registerQuickFixAction( highlightInfo, HighlightMethodUtil.getFixRange(field), QUICK_FIX_FACTORY.createInitializeFinalFieldInConstructorFix(field)); final PsiClass containingClass = field.getContainingClass(); if (containingClass != null && !containingClass.isInterface()) { QuickFixAction.registerQuickFixAction( highlightInfo, QUICK_FIX_FACTORY.createModifierListFix(field, PsiModifier.FINAL, false, false)); } QuickFixAction.registerQuickFixAction( highlightInfo, QUICK_FIX_FACTORY.createAddVariableInitializerFix(field)); return highlightInfo; }
public SNode convertField(PsiField x, SNode parentConcept) { SNode field; if (isStatic(x) || SConceptOperations.isSubConceptOf( parentConcept, "jetbrains.mps.baseLanguage.structure.Interface")) { field = SConceptOperations.createNewNode( "jetbrains.mps.baseLanguage.structure.StaticFieldDeclaration", null); } else { field = SConceptOperations.createNewNode( "jetbrains.mps.baseLanguage.structure.FieldDeclaration", null); SPropertyOperations.set( SNodeOperations.cast(field, "jetbrains.mps.baseLanguage.structure.FieldDeclaration"), "isVolatile", "" + (x.hasModifierProperty(PsiModifier.VOLATILE))); SPropertyOperations.set( SNodeOperations.cast(field, "jetbrains.mps.baseLanguage.structure.FieldDeclaration"), "isTransient", "" + (x.hasModifierProperty(PsiModifier.TRANSIENT))); } SPropertyOperations.set(field, "name", x.getName()); SLinkOperations.setTarget( SNodeOperations.cast(field, "jetbrains.mps.baseLanguage.structure.ClassifierMember"), "visibility", getVisibility(x), true); SPropertyOperations.set(field, "isFinal", "" + (isFinal(x))); SLinkOperations.setTarget(field, "type", convertType(x.getType()), true); addAnnotations(x, field); return field; }
private void processUsagesForMethod( final boolean deleteMethodHierarchy, PsiMethod method, int[] paramPermutation, String getterName, PsiMethod delegatedMethod, List<FixableUsageInfo> usages) { for (PsiReference reference : ReferencesSearch.search(method)) { final PsiElement referenceElement = reference.getElement(); final PsiMethodCallExpression call = (PsiMethodCallExpression) referenceElement.getParent(); final String access; if (call.getMethodExpression().getQualifierExpression() == null) { access = field.getName(); } else { access = getterName + "()"; if (getter == null) { getter = GenerateMembersUtil.generateGetterPrototype(field); } } usages.add( new InlineDelegatingCall(call, paramPermutation, access, delegatedMethod.getName())); } if (deleteMethodHierarchy) { usages.add(new DeleteMethod(method)); } }
public VariableLookupItem(PsiField field, boolean shouldImport) { super(field, field.getName()); myHelper = new MemberLookupHelper(field, field.getContainingClass(), shouldImport, false); if (!shouldImport) { forceQualify(); } }
public static void checkFieldConflicts( @Nullable PsiClass aClass, String newName, final Map<PsiElement, String> conflicts) { PsiField existingField = aClass != null ? aClass.findFieldByName(newName, true) : null; if (existingField != null) { if (aClass.equals(existingField.getContainingClass())) { String className = aClass instanceof PsiAnonymousClass ? RefactoringBundle.message("current.class") : RefactoringUIUtil.getDescription(aClass, false); final String conflict = RefactoringBundle.message( "field.0.is.already.defined.in.the.1", existingField.getName(), className); conflicts.put(existingField, conflict); } else { // method somewhere in base class if (!existingField.hasModifierProperty(PsiModifier.PRIVATE)) { String fieldInfo = PsiFormatUtil.formatVariable( existingField, PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.TYPE_AFTER, PsiSubstitutor.EMPTY); String className = RefactoringUIUtil.getDescription(existingField.getContainingClass(), false); final String descr = RefactoringBundle.message( "field.0.will.hide.field.1.of.the.base.class", newName, fieldInfo, className); conflicts.put(existingField, descr); } } } }
private static PsiField convertFieldToLanguage(PsiField field, Language language) { if (field.getLanguage().equals(language)) { return field; } return JVMElementFactories.getFactory(language, field.getProject()) .createField(field.getName(), field.getType()); }
@Override public void visitField(PsiField field) { // There is a possible case that more than one field is declared for the same type like 'int i, // j;'. We want to process only // the first one then. PsiElement fieldPrev = getPreviousNonWsComment(field.getPrevSibling(), 0); if (fieldPrev instanceof PsiJavaToken && ((PsiJavaToken) fieldPrev).getTokenType() == JavaTokenType.COMMA) { return; } // There is a possible case that fields which share the same type declaration are located on // different document lines, e.g.: // int i1, // i2; // We want to consider only the first declaration then but need to expand its range to all // affected lines (up to semicolon). TextRange range = field.getTextRange(); PsiElement child = field.getLastChild(); boolean needSpecialProcessing = true; if (isSemicolon(child)) { needSpecialProcessing = false; } else if (child instanceof PsiComment) { // There is a possible field definition like below: // int f; // my comment. // The comment goes into field PSI here, that's why we need to handle it properly. PsiElement prev = getPreviousNonWsComment(child, range.getStartOffset()); needSpecialProcessing = prev != null && !isSemicolon(prev); } if (needSpecialProcessing) { for (PsiElement e = field.getNextSibling(); e != null; e = e.getNextSibling()) { if (e instanceof PsiWhiteSpace || e instanceof PsiComment) { // Skip white space and comment continue; } else if (e instanceof PsiJavaToken) { if (((PsiJavaToken) e).getTokenType() == JavaTokenType.COMMA) { // Skip comma continue; } else { break; } } else if (e instanceof PsiField) { PsiElement c = e.getLastChild(); if (c != null) { c = getPreviousNonWsComment(c, range.getStartOffset()); } // Stop if current field ends by a semicolon. if (c instanceof PsiErrorElement // Incomplete field without trailing semicolon || (c instanceof PsiJavaToken && ((PsiJavaToken) c).getTokenType() == JavaTokenType.SEMICOLON)) { range = TextRange.create(range.getStartOffset(), c.getTextRange().getEndOffset()); } else { continue; } } break; } } JavaElementArrangementEntry entry = createNewEntry(field, range, FIELD, field.getName(), true); processEntry(entry, field, field.getInitializer()); }
@Override public LightRef asLightUsage(@NotNull PsiElement element, @NotNull ByteArrayEnumerator names) { if (mayBeVisibleOutsideOwnerFile(element)) { if (element instanceof PsiField) { final PsiField field = (PsiField) element; final PsiClass aClass = field.getContainingClass(); if (aClass == null || aClass instanceof PsiAnonymousClass) return null; final String jvmOwnerName = ClassUtil.getJVMClassName(aClass); final String name = field.getName(); if (name == null || jvmOwnerName == null) return null; return new LightRef.JavaLightFieldRef(id(jvmOwnerName, names), id(name, names)); } else if (element instanceof PsiMethod) { final PsiClass aClass = ((PsiMethod) element).getContainingClass(); if (aClass == null || aClass instanceof PsiAnonymousClass) return null; final String jvmOwnerName = ClassUtil.getJVMClassName(aClass); if (jvmOwnerName == null) return null; final PsiMethod method = (PsiMethod) element; final String name = method.isConstructor() ? "<init>" : method.getName(); final int parametersCount = method.getParameterList().getParametersCount(); return new LightRef.JavaLightMethodRef( id(jvmOwnerName, names), id(name, names), parametersCount); } else if (element instanceof PsiClass) { final String jvmClassName = ClassUtil.getJVMClassName((PsiClass) element); if (jvmClassName != null) { return new LightRef.JavaLightClassRef(id(jvmClassName, names)); } } } return null; }
private static String gettext(PsiField field, PsiType uiComponentType) { return UIDesignerBundle.message( "action.change.field.type", field.getName(), field.getType().getCanonicalText(), uiComponentType.getCanonicalText()); }
protected void generatePsiElements( @NotNull PsiField psiField, @NotNull PsiAnnotation psiAnnotation, @NotNull List<? super PsiElement> target) { final String fieldName = psiField.getName(); final PsiType psiFieldType = psiField.getType(); final String methodName = getFindByName(psiField); PsiClass psiClass = psiField.getContainingClass(); assert psiClass != null; UserMapKeys.addWriteUsageFor(psiField); LombokLightMethodBuilder method = new LombokLightMethodBuilder(psiField.getManager(), methodName) .withMethodReturnType(PsiTypesUtil.getClassType(psiClass)) .withContainingClass(psiClass) .withParameter(fieldName, psiFieldType) .withNavigationElement(psiField); method.withModifier(PsiModifier.STATIC); method.withModifier(PsiModifier.PUBLIC); target.add(method); }
@NonNls private static String computeConstantBooleanText(PsiExpression expression) { if (!(expression instanceof PsiReferenceExpression)) { return null; } final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) expression; final PsiElement target = referenceExpression.resolve(); if (!(target instanceof PsiField)) { return null; } final PsiField field = (PsiField) target; final PsiClass containingClass = field.getContainingClass(); if (containingClass == null) { return null; } final String qualifiedName = containingClass.getQualifiedName(); if (!CommonClassNames.JAVA_LANG_BOOLEAN.equals(qualifiedName)) { return null; } @NonNls final String name = field.getName(); if ("TRUE".equals(name)) { return "true"; } else if ("FALSE".equals(name)) { return "false"; } else { return null; } }
/** Create fields for injections inside main class */ protected void generateFields() { for (Iterator<Element> iterator = mElements.iterator(); iterator.hasNext(); ) { Element element = iterator.next(); if (!element.used) { iterator.remove(); continue; } // remove duplicate field PsiField[] fields = mClass.getFields(); boolean duplicateField = false; for (PsiField field : fields) { String name = field.getName(); if (name != null && name.equals(element.getFieldName())) { duplicateField = true; break; } } if (duplicateField) { iterator.remove(); continue; } mClass.add( mFactory.createFieldFromText( "private " + element.name + " " + element.getFieldName() + ";", mClass)); } }
private static PsiAnnotationMemberValue[] readFromClass( @NonNls String attributeName, @NotNull PsiAnnotation magic, PsiType type) { PsiAnnotationMemberValue fromClassAttr = magic.findAttributeValue(attributeName); PsiType fromClassType = fromClassAttr instanceof PsiClassObjectAccessExpression ? ((PsiClassObjectAccessExpression) fromClassAttr).getOperand().getType() : null; PsiClass fromClass = fromClassType instanceof PsiClassType ? ((PsiClassType) fromClassType).resolve() : null; if (fromClass == null) return null; String fqn = fromClass.getQualifiedName(); if (fqn == null) return null; List<PsiAnnotationMemberValue> constants = new ArrayList<PsiAnnotationMemberValue>(); for (PsiField field : fromClass.getFields()) { if (!field.hasModifierProperty(PsiModifier.PUBLIC) || !field.hasModifierProperty(PsiModifier.STATIC) || !field.hasModifierProperty(PsiModifier.FINAL)) continue; PsiType fieldType = field.getType(); if (!Comparing.equal(fieldType, type)) continue; PsiAssignmentExpression e = (PsiAssignmentExpression) JavaPsiFacade.getElementFactory(field.getProject()) .createExpressionFromText("x=" + fqn + "." + field.getName(), field); PsiReferenceExpression refToField = (PsiReferenceExpression) e.getRExpression(); constants.add(refToField); } if (constants.isEmpty()) return null; return constants.toArray(new PsiAnnotationMemberValue[constants.size()]); }
@Override public PsiField findFieldByName(@NonNls String name, boolean checkBases) { final PsiField[] fields = getFields(); for (final PsiField field : fields) { if (name.equals(field.getName())) return field; } return null; }
/** * judge field exists * * @param part * @return */ private boolean fieldExist(ViewPart part) { PsiField[] fields = mClass.getAllFields(); for (PsiField field : fields) { if (field.getName().equals(part.getName())) { return true; } } return false; }
private void generateToString(PsiClass psiClass, List<PsiField> fields) { StringBuilder builder = new StringBuilder("@Override\n"); builder.append("public String toString() { \n"); builder .append("return ") .append(COM_GOOGLE_COMMON_BASE_MORE_OBJECTS) .append(".toStringHelper(this)\n"); for (PsiField field : fields) { builder .append(".add(\"") .append(field.getName()) .append("\", ") .append(field.getName()) .append(")\n"); } builder.append(".toString();\n}"); setNewMethod(psiClass, builder.toString(), "toString"); }
private boolean existsFieldWithName(String name) { final PsiField[] allFields = sourceClass.getAllFields(); for (PsiField field : allFields) { if (name.equals(field.getName()) && !fields.contains(field)) { return true; } } return false; }
@NotNull private Field fieldToField(@NotNull PsiField field, PsiClass psiClass) { Set<String> modifiers = modifiersListToModifiersSet(field.getModifierList()); if (field instanceof PsiEnumConstant) // TODO: remove instanceof { return new EnumConstant( new IdentifierImpl(field.getName()), // TODO modifiers, typeToType(field.getType()), elementToElement(((PsiEnumConstant) field).getArgumentList())); } return new Field( new IdentifierImpl(field.getName()), // TODO modifiers, typeToType(field.getType(), ConverterUtil.isAnnotatedAsNotNull(field.getModifierList())), createSureCallOnlyForChain(field.getInitializer(), field.getType()), // TODO: add modifiers countWritingAccesses(field, psiClass)); }
@Override public void writeMethod(PsiCodeBlock methodBody, PsiElementFactory factory, PsiField field) { if (null == methodBody) { return; } // out.writeTypedList(p); methodBody.add( factory.createStatementFromText("out.writeTypedList(" + field.getName() + ");", null)); }
private static PsiStatement addInitializationToConstructors( PsiLocalVariable local, PsiField field, PsiMethod enclosingConstructor, PsiElementFactory factory) throws IncorrectOperationException { PsiClass aClass = field.getContainingClass(); PsiMethod[] constructors = aClass.getConstructors(); PsiStatement assignment = createAssignment(local, field.getName(), factory); boolean added = false; for (PsiMethod constructor : constructors) { if (constructor == enclosingConstructor) continue; PsiCodeBlock body = constructor.getBody(); if (body == null) continue; PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { PsiStatement first = statements[0]; if (first instanceof PsiExpressionStatement) { PsiExpression expression = ((PsiExpressionStatement) first).getExpression(); if (expression instanceof PsiMethodCallExpression) { @NonNls String text = ((PsiMethodCallExpression) expression).getMethodExpression().getText(); if ("this".equals(text)) { continue; } if ("super".equals(text) && enclosingConstructor == null && PsiTreeUtil.isAncestor(constructor, local, false)) { local.delete(); return (PsiStatement) body.addAfter(assignment, first); } } } if (enclosingConstructor == null && PsiTreeUtil.isAncestor(constructor, local, false)) { local.delete(); return (PsiStatement) body.addBefore(assignment, first); } } assignment = (PsiStatement) body.add(assignment); added = true; } if (!added && enclosingConstructor == null) { if (aClass instanceof PsiAnonymousClass) { final PsiClassInitializer classInitializer = (PsiClassInitializer) aClass.addAfter(factory.createClassInitializer(), field); assignment = (PsiStatement) classInitializer.getBody().add(assignment); } else { PsiMethod constructor = (PsiMethod) aClass.add(factory.createConstructor()); assignment = (PsiStatement) constructor.getBody().add(assignment); } } if (enclosingConstructor == null) local.delete(); return assignment; }
@Override public void findExistingNameConflicts( PsiElement element, String newName, MultiMap<PsiElement, String> conflicts) { if (element instanceof PsiCompiledElement) return; if (element instanceof PsiField) { PsiField refactoredField = (PsiField) element; if (newName.equals(refactoredField.getName())) return; ConflictsUtil.checkFieldConflicts(refactoredField.getContainingClass(), newName, conflicts); } }
@Override protected List<EncapsulatableClassMember> getEncapsulatableClassMembers(PsiClass psiClass) { final List<EncapsulatableClassMember> result = new ArrayList<EncapsulatableClassMember>(); for (PsiField field : psiClass.getFields()) { if (null != PropertyUtil.findPropertySetter(psiClass, field.getName(), false, false)) { result.add(new PsiFieldMember(field)); } } return result; }
public static PsiMethod generateSetterPrototype( PsiField field, final PsiClass containingClass, boolean returnSelf) { Project project = field.getProject(); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory(); String name = field.getName(); boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); VariableKind kind = codeStyleManager.getVariableKind(field); String propertyName = codeStyleManager.variableNameToPropertyName(name, kind); String setName = suggestSetterName(project, field); try { PsiMethod setMethod = factory.createMethod( setName, returnSelf ? factory.createType(containingClass) : PsiType.VOID); String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER); PsiParameter param = factory.createParameter(parameterName, field.getType()); annotateWithNullableStuff(field, factory, param); setMethod.getParameterList().add(param); PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true); PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic); @NonNls StringBuffer buffer = new StringBuffer(); buffer.append("{\n"); if (name.equals(parameterName)) { if (!isStatic) { buffer.append("this."); } else { String className = containingClass.getName(); if (className != null) { buffer.append(className); buffer.append("."); } } } buffer.append(name); buffer.append("="); buffer.append(parameterName); buffer.append(";\n"); if (returnSelf) { buffer.append("return this;\n"); } buffer.append("}"); PsiCodeBlock body = factory.createCodeBlockFromText(buffer.toString(), null); setMethod.getBody().replace(body); setMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(setMethod); return setMethod; } catch (IncorrectOperationException e) { LOG.error(e); return null; } }
/** * Create a new {@link FieldElement} object. * * @param field the {@link com.intellij.psi.PsiField} to get the information from. * @return a new {@link FieldElement} object. */ public static FieldElement newFieldElement(PsiField field, boolean useAccessor) { FieldElement fe = new FieldElement(); fe.setName(field.getName()); final PsiMethod getterForField = useAccessor ? PropertyUtil.findGetterForField(field) : null; fe.setAccessor(getterForField != null ? getterForField.getName() + "()" : field.getName()); if (PsiAdapter.isConstantField(field)) fe.setConstant(true); if (PsiAdapter.isEnumField(field)) fe.setEnum(true); PsiModifierList modifiers = field.getModifierList(); if (modifiers != null) { if (modifiers.hasModifierProperty(PsiModifier.TRANSIENT)) fe.setModifierTransient(true); if (modifiers.hasModifierProperty(PsiModifier.VOLATILE)) fe.setModifierVolatile(true); } PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory(); PsiType type = field.getType(); setElementInfo(fe, factory, type, modifiers); return fe; }
public ChangeFieldTypeFix(GuiEditor uiEditor, PsiField field, PsiType uiComponentType) { super( uiEditor, MessageFormat.format( UIDesignerBundle.message("action.change.field.type"), field.getName(), field.getType().getCanonicalText(), uiComponentType.getCanonicalText()), null); myField = field; myNewType = uiComponentType; }
@Test public void shouldVerifyThatFieldIsSetInSetterMethodIfItHasNoModifierListAndHasCorrectParameter() { // given given(psiClass.getAllMethods()).willReturn(methods); given(psiField.getName()).willReturn("field"); given(method.getName()).willReturn("setField"); // when boolean result = psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); // then assertThat(result, is(true)); }
@Test public void shouldVerifyThatFieldIsNotSetInSetterMethodIfItIsPrivate() { // given given(psiClass.getAllMethods()).willReturn(methods); given(method.getModifierList()).willReturn(modifierList); given(psiField.getName()).willReturn("field"); given(modifierList.hasExplicitModifier(PsiFieldVerifierImpl.PRIVATE_MODIFIER)).willReturn(true); given(method.getName()).willReturn("setField"); // when boolean result = psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); // then assertThat(result, is(false)); }
@Test public void shouldVerifyThatFieldIsNotSetInSetterMethodIfItIsNotPrivateButHasIncorrectParameter() { // given given(psiClass.getAllMethods()).willReturn(methods); given(method.getModifierList()).willReturn(modifierList); given(psiField.getName()).willReturn("field"); given(method.getName()).willReturn("setAnotherField"); // when boolean result = psiFieldVerifier.isSetInSetterMethod(psiField, psiClass); // then assertThat(result, is(false)); }