如何创建一个简单的示例控制台应用程序来开发单独的类以进行测试驱动开发?

发布于 2024-07-18 04:08:06 字数 5914 浏览 4 评论 0原文

我的目的是创建一个简单的、易于调试的控制台应用程序,它将作为 C# 中测试驱动开发单个类的模板(或起点)。 目的是拥有一个简单的文件夹,该控制台应用程序将驻留在该文件夹中,只需复制粘贴该文件夹即可打开新项目并开始编写新类。 一旦类的所有功能都经过测试(最好测试应该在同一个文件(或至少命名空间)中),该类将被允许进入更大的项目。我正在使用 NUnit 和 log4net。如果你这样做“小型测试驱动单元构建”方法您是如何实现的,请发布一些代码或解释,如果您不使用,请解释原因? 这是代码(配置数据也作为注释粘贴......)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using log4net.Config;
using NUnit.Framework;

namespace NUnitSimple
{

  class TheClassToTest_Substractor
  {

    private static readonly ILog logger =
         LogManager.GetLogger ( typeof ( TheClassToTest_Substractor ) );



    public static void Substract ( int intToSusbractFrom , int intToSubstract , ref int intTheResult)
    {
     intTheResult = intToSusbractFrom - intToSubstract ; 
    }


    static void Main ( string[] args )
    {
      DOMConfigurator.Configure (); //tis configures the logger 


      logger.Info ( " START " );
      logger.Info ( " Hit a key to exit " );
      Console.ReadLine ();


    } //eof method 



  } //eof class 

  [TestFixture]//telling NUnit that this class contains test functions 
public class TestTheClassToTest_Substractor
{ 

     [Test]//telling NUnit that this function should be run during the tests 
    public void TestSubstractOk() 
    { 
       int intToSusbractFrom = 10 ; 
       int intToSubstract = 4 ; 
        int intTheResult = 0 ;
       TheClassToTest_Substractor.Substract ( intToSusbractFrom , intToSubstract , ref intTheResult ) ;
        Assert.AreEqual (  6 , intTheResult);
    }



     [Test]//telling NUnit that this function should be run during the tests 
     public void TestSubstractNOK ()
     {
       int intToSusbractFrom = 10;
       int intToSubstract = 4;
       int intTheResult = 0;
       TheClassToTest_Substractor.Substract ( intToSusbractFrom, intToSubstract, ref intTheResult );
       Assert.AreNotEqual ( 3, intTheResult );
     }

} //eof class 


} //eof namespace 




#region TheAppConfig
/*
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net"
         type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <param name="File" value="Program.log" />
      <param name="AppendToFile" value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="[Header] \r\n" />
        <param name="Footer" value="[Footer] \r\n" />
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
      </layout>
    </appender>

    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="ERROR" />
        <foreColor value="White" />
        <backColor value="Red, HighIntensity" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>


    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.2.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionString value="data source=ysg;initial catalog=DBGA_DEV;integrated security=true;persist security info=True;" />
      <commandText value="INSERT INTO [DBGA_DEV].[ga].[tb_Data_Log] ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />

      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
      </parameter>
      <parameter>
        <parameterName value="@thread" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout" value="%thread" />
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout" value="%level" />
      </parameter>
      <parameter>
        <parameterName value="@logger" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout" value="%logger" />
      </parameter>
      <parameter>
        <parameterName value="@message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout" value="%messag2e" />
      </parameter>
    </appender>
    <root>
      <level value="INFO" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="AdoNetAppender" />
      <appender-ref ref="ColoredConsoleAppender" />
    </root>
  </log4net>
</configuration>
 */
#endregion TheAppconfig

#region TheXmlReferingToTheNUnitAndLog4NetInNUnitSimple.csprojFile
/*
     <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\..\Log4Net\log4net-1.2.10\bin\net\2.0\release\log4net.dll</HintPath>
    </Reference>
    <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" />
 */
#endregion

My intend is to create a simple easily debuggable console application which will be the template ( or starting point ) for test driven developing single classes in C#. The purpose is to have a simple folder where this console app will reside and just copy paste the folder open the new project and start writing the new class. As soon as the class all functionalities tested ( Preferably the tests should be in the same file ( or at least namespace ) the class will be allowed to go into the larger project. I am using NUnit and log4net. If you do you this kind of "small test driven unit building " approach how have you implemented it. Please, post some code or explanation. If you do not use, please provide explanation why?
Here is the code ( the config data is also pasted as comments ... )

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using log4net.Config;
using NUnit.Framework;

namespace NUnitSimple
{

  class TheClassToTest_Substractor
  {

    private static readonly ILog logger =
         LogManager.GetLogger ( typeof ( TheClassToTest_Substractor ) );



    public static void Substract ( int intToSusbractFrom , int intToSubstract , ref int intTheResult)
    {
     intTheResult = intToSusbractFrom - intToSubstract ; 
    }


    static void Main ( string[] args )
    {
      DOMConfigurator.Configure (); //tis configures the logger 


      logger.Info ( " START " );
      logger.Info ( " Hit a key to exit " );
      Console.ReadLine ();


    } //eof method 



  } //eof class 

  [TestFixture]//telling NUnit that this class contains test functions 
public class TestTheClassToTest_Substractor
{ 

     [Test]//telling NUnit that this function should be run during the tests 
    public void TestSubstractOk() 
    { 
       int intToSusbractFrom = 10 ; 
       int intToSubstract = 4 ; 
        int intTheResult = 0 ;
       TheClassToTest_Substractor.Substract ( intToSusbractFrom , intToSubstract , ref intTheResult ) ;
        Assert.AreEqual (  6 , intTheResult);
    }



     [Test]//telling NUnit that this function should be run during the tests 
     public void TestSubstractNOK ()
     {
       int intToSusbractFrom = 10;
       int intToSubstract = 4;
       int intTheResult = 0;
       TheClassToTest_Substractor.Substract ( intToSusbractFrom, intToSubstract, ref intTheResult );
       Assert.AreNotEqual ( 3, intTheResult );
     }

} //eof class 


} //eof namespace 




#region TheAppConfig
/*
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net"
         type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <param name="File" value="Program.log" />
      <param name="AppendToFile" value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="[Header] \r\n" />
        <param name="Footer" value="[Footer] \r\n" />
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
      </layout>
    </appender>

    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="ERROR" />
        <foreColor value="White" />
        <backColor value="Red, HighIntensity" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>


    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.2.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionString value="data source=ysg;initial catalog=DBGA_DEV;integrated security=true;persist security info=True;" />
      <commandText value="INSERT INTO [DBGA_DEV].[ga].[tb_Data_Log] ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />

      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
      </parameter>
      <parameter>
        <parameterName value="@thread" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout" value="%thread" />
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout" value="%level" />
      </parameter>
      <parameter>
        <parameterName value="@logger" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout" value="%logger" />
      </parameter>
      <parameter>
        <parameterName value="@message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout" value="%messag2e" />
      </parameter>
    </appender>
    <root>
      <level value="INFO" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="AdoNetAppender" />
      <appender-ref ref="ColoredConsoleAppender" />
    </root>
  </log4net>
</configuration>
 */
#endregion TheAppconfig

#region TheXmlReferingToTheNUnitAndLog4NetInNUnitSimple.csprojFile
/*
     <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\..\Log4Net\log4net-1.2.10\bin\net\2.0\release\log4net.dll</HintPath>
    </Reference>
    <Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" />
 */
#endregion

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

任谁 2024-07-25 04:08:06

与其建立一个项目然后剪切和粘贴,为什么不查看像 Tree Surgeon 这样的脚本工具来建立项目结构。 这将设置您的解决方案、项目和项目文件夹。 它包括 nUnit 和 nAnt 的功能。

请务必查看项目主页底部镜像的博客文章。

顺便说一句:我同意 Jon Skeet 关于控制台应用程序的观点。 它们可能很有用,但如果您有用于 VS.2005 及更早版本的 TestDriven.Net 之类的工具,或者使用 VS.2008 测试工具,您可以单步执行测试代码,而无需创建自己的线束应用程序。

Rather than set up a a project and then cut and paste, why not look at a script tool like Tree Surgeon to set up a project structure. This will set up your solution, projects and project folders. It includes functionality for both nUnit and nAnt.

Be sure to look at the blog posts mirrored at the bottom of the project home page.

BTW: I agree with Jon Skeet on console apps. They can be useful, but if you have a tool like TestDriven.Net for VS.2005 and earlier, or the VS.2008 testing tools, you can step into your test code without creating your own harness app.

轮廓§ 2024-07-25 04:08:06

我真的不明白在现有项目中包含新类,在现有测试项目中包含新测试类并在那里运行测试有什么好处。

为什么要引入控制台应用程序? 您真的需要从控制台应用程序而不是从现有的测试运行程序之一运行测试吗? (不要误会我的意思,我是控制台应用程序的忠实粉丝 - 我只是不明白它们如何适合这里。)

I don't really see what the benefit is over including the new class in the existing project, including the new test class in the existing test project, and running the tests there.

Why introduce a console app? Do you really need to run the tests from a console app rather than from one of the existing test runners? (Don't get me wrong, I'm a big fan of console apps - I just don't see how they fit in here.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文