Example #1
0
        /// <summary>
        /// Implements the mock code.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="codeSnippet">The code snippet.</param>
        public static void ImplementMockCode(
            this CodeClass instance,
            CodeSnippet codeSnippet)
        {
            TraceService.WriteLine("CodeClassExtensions::ImplementMockCode file=" + instance.Name);

            CodeFunction codeFunction = instance.GetFunction(codeSnippet.TestInitMethod);

            if (codeFunction != null)
            {
                if (string.IsNullOrEmpty(codeSnippet.GetMockInitCode()) == false)
                {
                    codeFunction.InsertCode(codeSnippet.GetMockInitCode(), true);
                }

                if (string.IsNullOrEmpty(codeSnippet.GetMockConstructorCode()) == false)
                {
                    string code = codeFunction.GetCode();

                    string testFileName = instance.Name;

                    //// remove Test at the start - need a better way of doing this!
                    string fileName = testFileName.Replace("Test", string.Empty);

                    //// TODO : this wont always work if the function spans multiple lines!
                    int index = code.IndexOf(fileName + "(", StringComparison.Ordinal);

                    if (index != 0)
                    {
                        string seperator = string.Empty;

                        //// here we are looking for the closing bracket
                        //// if we dont have a closing bracket then we already have something
                        //// on the constructor and therefore need a ',' to make it work!
                        if (code.Substring(index + fileName.Length + 1, 1) != ")")
                        {
                            //// TODO : do we want to create a new line too!
                            seperator = ", ";
                        }

                        StringBuilder sb = new StringBuilder();
                        sb.Append(code.Substring(0, index + fileName.Length + 1));
                        sb.Append(codeSnippet.GetMockConstructorCode() + seperator);
                        sb.Append(code.Substring(index + fileName.Length + 1));

                        codeFunction.ReplaceCode(sb.ToString());
                    }
                }
            }
        }