本文介绍了NUnit测试Stylecop自定义规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我目前正在从事单元测试,Stylecop自定义规则的工作,我试图使用NUnit V2.6对我的Stylecop规则进行测试,但是我尝试了很多时间将Stylecop实体转换为字符串,但这是行不通的.以下是我尝试使用的示例代码

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

[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);
    }



正如我试图在NUnit中打印错误消息一样,但这是因为像NUnit测试一样,它并不能容纳任何对象和Stylecop元素.寻求有关如何将OutputEventArgs转换为String并将其在NUnit Testing平台中打印出来的建议

谢谢



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

推荐答案

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





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>


这篇关于NUnit测试Stylecop自定义规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 06:58