Click here to Skip to main content
15,886,963 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

I am currently working on Unit Testing, Stylecop custom rules, i tried to use NUnit V2.6 to test on my Stylecop rules, but i tried lots of time to convert Stylecop entity to string it doesn't work. below is the example code i was trying to work on
C#
[TestFixture]
public class MyCalPath
{

    public static void main(string[] args)
    {
        string projectPath = @"C:\Documents and Settings\NickyPhun\My Documents\Visual Studio 2010\Projects\MyCustomRules3\MyCustomRules3";
        string filePath = @"C:\Documents and Settings\NickyPhun\My Documents\Visual Studio 2010\Projects\MyCustomRules3\MyCustomRules3\MyCal.cs";
        StyleCopConsole console = new StyleCopConsole(null, false, null, null, true);
        CodeProject project = new CodeProject(0, projectPath, new Configuration(null));
        console.Core.Environment.AddSourceCode(project, filePath, null);
        console.OutputGenerated += OnOutputGenerated;
        console.ViolationEncountered += OnViolationEncountered;
        console.Start(new[] { project }, true);
        console.OutputGenerated -= OnOutputGenerated;
        console.ViolationEncountered -= OnViolationEncountered;

    }
    [Test]
    public static void OnOutputGenerated(object sender,OutputEventArgs e)
    {
        Console.WriteLine(e.Output);
    }
    [Test]
    public static void OnViolationEncountered(object sender, ViolationEventArgs e)
    {
        Console.WriteLine("{0}: {1}", e.Violation.Rule.CheckId, e.Message);
    }


as i was trying to print out the error messagein NUnit, but it since like NUnit testing doesn't acceot any object and Stylecop element. seeking advice on how i able to conver OutputEventArgs to String and print it out in NUnit Testing platform

Thank you
Posted

1 solution

Extract from Clean Coders StyleCop Rules

Your cast seems bad. You are looking at a syntax similar to this:

C#
this.StyleCopConsole.ViolationEncountered += (sender, args) => this.StyleCopViolations.Add(args.Violation);


C#
namespace CleanCodersStyleCopRules.Test
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;

    using NUnit.Framework;

    using StyleCop;

    /// <summary>
    /// Base class for all TestFixture testing StyleCop custom rules.
    /// </summary>
    [TestFixture]
    public abstract class TestFixtureBase
    {
        #region Constants and Fields

        /// <summary>
        ///   The code project.
        /// </summary>
        private CodeProject codeProject;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        ///   Initializes a new instance of the <see cref="TestFixtureBase" /> class.
        /// </summary>
        protected TestFixtureBase()
        {
            string settings = AppDomain.CurrentDomain.BaseDirectory + @"\Resources\Settings.StyleCop";

            List<string> addInPath = new List<string> { AppDomain.CurrentDomain.BaseDirectory };

            this.StyleCopConsole = new StyleCopConsole(settings, false, null, addInPath, true);

            this.StyleCopConsole.ViolationEncountered += (sender, args) => this.StyleCopViolations.Add(args.Violation);

            this.StyleCopConsole.OutputGenerated += (sender, args) => this.StyleCopOutput.Add(args.Output);
        }

        #endregion

        #region Properties

        /// <summary>
        ///   Gets the StyleCop output.
        /// </summary>
        protected List<string> StyleCopOutput { get; private set; }

        /// <summary>
        ///   Gets the StyleCop violations.
        /// </summary>
        protected List<violation> StyleCopViolations { get; private set; }

        /// <summary>
        ///   Gets or sets the StyleCop Console.
        /// </summary>
        private StyleCopConsole StyleCopConsole { get; set; }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// Configure the CodeProject.
        /// </summary>
        [SetUp]
        public void Setup()
        {
            this.StyleCopViolations = new List<violation>();

            this.StyleCopOutput = new List<string>();

            string settings = AppDomain.CurrentDomain.BaseDirectory + @"\Resources";

            Configuration configuration = new Configuration(new string[0]);

            this.codeProject = new CodeProject(Guid.NewGuid().GetHashCode(), settings, configuration);
        }

        /// <summary>
        /// Clean up the test.
        /// </summary>
        [TearDown]
        public void TearDown()
        {
            this.codeProject = null;

            this.StyleCopViolations.Clear();

            this.StyleCopOutput.Clear();
        }

        #endregion

        #region Methods

        /// <summary>
        /// Analyzes the code file.
        /// </summary>
        /// <param name="sourceCodeFileName">
        /// The code file name (file name with extention, not the full path. File must be located in the Resources directory)
        /// </param>
        /// <param name="numberOfExpectedViolation">
        /// The number of expected violations.
        /// </param>
        protected void AnalyzeCodeWithAssertion(string sourceCodeFileName, int numberOfExpectedViolation)
        {
            this.AddSourceCode(sourceCodeFileName);

            this.StartAnalysis();

            this.WriteViolationsToConsole();

            this.WriteOutputToConsole();

            Assert.AreEqual(numberOfExpectedViolation, this.StyleCopViolations.Count);
        }

        /// <summary>
        /// The write violations to console.
        /// </summary>
        protected void WriteViolationsToConsole()
        {
            foreach (Violation violation in this.StyleCopViolations)
            {
                Console.WriteLine(violation.Message);
            }
        }

        /// <summary>
        /// Dynamically add a source file to test.
        /// </summary>
        /// <param name="sourceCodeFileName">
        /// The file name.
        /// </param>
        /// <exception cref="ArgumentException">
        /// Occurs if the file could not be loaded from the Resources directory.
        /// </exception>
        private void AddSourceCode(string sourceCodeFileName)
        {
            string fullSourceCodeFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\Resources\" + sourceCodeFileName;

            bool result = this.StyleCopConsole.Core.Environment.AddSourceCode(this.codeProject, fullSourceCodeFilePath, null);

            if (result == false)
            {
                throw new ArgumentException("Source code file could not be loaded.", sourceCodeFileName);
            }
        }

        /// <summary>
        /// Starts the analysis of the code file with StyleCop.
        /// </summary>
        private void StartAnalysis()
        {
            CodeProject[] projects = new[] { this.codeProject };

            bool result = this.StyleCopConsole.Start(projects, true);

            if (result == false)
            {
                throw new ArgumentException("StyleCopConsole.Start had a problem.");
            }
        }

        /// <summary>
        /// The write output to console.
        /// </summary>
        private void WriteOutputToConsole()
        {
            Console.WriteLine(string.Join(Environment.NewLine, this.StyleCopOutput.ToArray()));
        }

        #endregion
    }
}
</string></violation></violation></string></string></string>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900