private static void AddMocksToClassDeclaration(IMethodDeclaration methodDeclaration, IObjectCreationExpression ctorExpression, MockInfo[] mockInfos, IClassDeclaration classDeclaration, CSharpElementFactory factory) { var ctorStatement = methodDeclaration.Body.Statements .FirstOrDefault(x => { var expression = (x as IExpressionStatement)?.Expression; if (expression != null && (expression == ctorExpression || (expression as IAssignmentExpression)?.Source == ctorExpression)) { return(true); } var declarationStatement = (x as IDeclarationStatement); if (declarationStatement?.VariableDeclarations.Any(varDeclaration => (varDeclaration.Initial as IExpressionInitializer)?.Value == ctorExpression) ?? false) { return(true); } return(false); }); foreach (var mockInfo in mockInfos) { classDeclaration.AddMemberDeclaration(mockInfo.Type, mockInfo.Name, factory, m => m.All(x => x.DeclaredName != mockInfo.Name)); var elementHasAssigned = methodDeclaration.Body.Statements.Any(x => { var assignmentOperands = ((x as IExpressionStatement)?.Expression as IAssignmentExpression)?.OperatorOperands; return(assignmentOperands != null && assignmentOperands.Any(operand => (operand as IReferenceExpression)?.NameIdentifier.Name == mockInfo.Name)); }); if (!elementHasAssigned) { methodDeclaration.Body.AddStatementBefore(mockInfo.Statement, ctorStatement); } } }