Test-Driven Development in .NET摘要

原创 2004年08月18日 10:32:00

Test-Driven Development in .NET
http://www.codeproject.com/dotnet/tdd_in_dotnet.asp

摘要:

Using Mock Objects - DotNetMock

One of the biggest challenges you will face when writing units tests is to make sure that each test is only testing one thing. It is very common to have a situation where the method you are testing uses other objects to do its work. If you write a test for this method you end up testing not only the code in that method, but also code in the other classes. This is a problem. Instead we use mock objects to ensure that we are only testing the code we intend to test. A mock object emulates a real class and helps test expectations about how that class is used. Most importantly, mock objects are:

  1. Easy to make
  2. Easy to set up
  3. Fast
  4. Deterministic (produce predictable results)
  5. Allow easy verification the correct calls were made, perhaps in the right order

The following example shows a typical mock object usage scenario. Notice that the test code is clean, easy to understand and not dependent on anything except the code being tested.

namespace UnitTestingExamples.Tests
{
  using DotNetMock;
  using System;

  [TestFixture]
  public class ModelTests
  {
    [Test]
    public void TestSave()
    {
      MockDatabase db = new MockDatabase();
      db.SetExpectedUpdates(2);

      ModelClass model = new ModelClass();
      model.Save( db );

      db.Verify();
    }
  }
}

As you can see, the MockDatabase was easy to setup and allowed us to confirm that the Save method made certain calls on it. Also notice that the mock object prevents us from having to worry about real databases. We know that when the ModelClass saves itself, it should call the database's Update method twice. So we tell the MockDatabase to expect two updates calls, call Save and the confirm that what we expected really happened. Because the MockDatabase doesn't really connect to a database, we don't have to worry about keeping "test data" around. We only test that the Save code causes two updates.

"When Mock Objects are used, only the unit test and the target domain code are real." -- Endo-Testing: Unit Testing with Mock Objects by Tim Mackinnon, Steve Freeman and Philip Craig.

Testing the Business Layer

Testing the business layer is where most developers feel comfortable talking about unit testing. Well designed business layer classes are loosely coupled and highly cohesive. In practical terms, coupling described the level of dependence that classes have with one another. If a class is loosely coupled, then making a change to one class should not have an impact on another class. On the other hand, a highly cohesive class is a class that does the one thing is was designed to do and nothing else. If you create your business layer class library so that the classes are loosely coupled and highly cohesive, then creating useful unit tests is easy. You should be able to create a single test class for each business class. You should be able to test each of its public methods with a minimal amount of effort. By the way, if you are having a difficult time creating unit tests for your business layer classes, then you probably need to do some significant refactoring. Of course, if you have been writing your tests first, you shouldn't have this problem.

Testing the User Interface

When you start to write the user interface for your application, a number of different problems arise. Although you can create user interface classes that are loosely coupled with respect to other classes, a user interface class is by definition highly coupled to the user! So how can we create a automated unit test to test this? The answer is that we separate the logic of our user interface from the actual presentation of the view. Various patterns exist in the literature under a variety of different names: Model-View-Controller, Model-View-Presenter, Doc-View, etc. The creators of these patterns recognized that decoupling the logic of what the view does (i.e., controller) from the view is a Good Thing. So how do we use this? The technique I use comes from Michael Feathers' paper The Humble Dialog Box. The idea is to make the view class support a simple interface used for getting and setting the values displayed by the view. There is basically no code in the view except for code related to the painting of the screen. The event handlers in the view for each interactive user interface element (e.g., a button) contain nothing more than a pass-thru to a method in the controller. The best way to illustrate this concept is with an example. Assume our application needs a screen that asks the user for their name and social security number. Both fields are required, so we need to make sure that a name is entered and the SSN has the correct format. Since we are writing our unit tests first, we write the following test:

[TestFixture]
public class VitalsControllerTests
{
        [Test]
        public void TestSuccessful()
        {
                MockVitalsView view = new MockVitalsView();
                VitalsController controller = new VitalsController(view);
                
                view.Name = "Peter Provost";
                view.SSN = "123-45-6789";
                
                Assertion.Assert( controller.OnOk() == true );
        }
        
        [Test]
        public void TestFailed()
        {
                MockVitalsView view = new MockVitalsView();
                VitalsController controller = new VitalsController(view);
                
                view.Name = "";
                view.SSN = "123-45-6789";
                view.SetExpectedErrorMessage( controller.ERROR_MESSAGE_BAD_NAME );
                Assertion.Assert( controller.OnOk() == false );
                view.Verify();
                
                view.Name = "Peter Provost";
                view.SSN = "";
                view.SetExpectedErrorMessage( controller.ERROR_MESSAGE_BAD_SSN );
                Assertion.Assert( controller.OnOk() == false );
                view.Verify()
                
        }
}

When we build this we receive a lot of compiler errors because we don't have either a MockVitalsView or a VitalsController. So let's write skeletons of those classes. Remember, we only want to write enough to make this code compile.

public class MockVitalsView
{
        public string Name
        {
                get { return null; }
                set { }
        }
        
        public string SSN
        {
                get { return null; }
                set { }
        }
        
        public void SetExpectedErrorMessage( string message )
        {
        }
        
        public void Verify()
        {
                throw new NotImplementedException();
        }
}

public class VitalsController
{
        public const string ERROR_MESSAGE_BAD_SSN = "Bad SSN.";
        public const string ERROR_MESSAGE_BAD_NAME = "Bad name.";
        
        public VitalsController( MockVitalsView view )
        {
        }
        
        public bool OnOk()
        {
                return false;
        }
}

Now our test assembly compiles and when we run the tests, the test runner reports two failures. The first occurs when TestSuccessful calls controller.OnOk, because the result is false rather than the expected true value. The second failure occurs when TestFailed calls view.Verify. Continuing on with our test-first paradigm, we now need to make these tests pass. It is relatively simple to make TestSuccessful pass, but to make TestFailed pass, we actually have to write some real code, such as:

public class MockVitalsView : MockObject
{
        public string Name
        {
                get { return _name; }
                set { _name = value; }
        }
        
        public string SSN
        {
                get { return _ssn; }
                set { _ssn = value; }
        }
        
        public string ErrorMessage
        {
                get { return _expectedErrorMessage.Actual; }
                set { _expectedErrorMessage.Actual = value; }
        }
        
        public void SetExpectedErrorMessage( string message )
        {
                _expectedErrorMessage.Expected = message;
        }
        
        private string _name;
        private string _ssn;
        private ExpectationString _expectedErrorMessage = 
          new ExpectationString("expected error message");
}

public class VitalsController
{
        public const string ERROR_MESSAGE_BAD_SSN = "Bad SSN.";
        public const string ERROR_MESSAGE_BAD_NAME = "Bad name.";
        
        public VitalsController( MockVitalsView view )
        {
                _view = view;
        }
        
        public bool OnOk()
        {
                if( IsValidName() == false )
                {
                        _view.ErrorMessage = ERROR_MESSAGE_BAD_NAME;
                        return false;
                }
                
                if( IsValidSSN() == false )
                {
                        _view.ErrorMessage = ERROR_MESSAGE_BAD_SSN;
                        return false;
                }
                
                // All is well, do something...
                
                return true;
        }
        
        private bool IsValidName()
        {
                return _view.Name.Length > 0;
        }
        
        private bool IsValidSSN()
        {
                string pattern = @"^/d{3}-/d{2}-/d{4}$";
                return Regex.IsMatch( _view.SSN, pattern );
        }
        
        private MockVitalsView _view;
}

Let's briefly review this code before proceeding. The first thing to notice is that we haven't changed the tests at all (which is why I didn't even bother to show them). We did, however, make significant changes to both MockVitalsView and VitalsController. Let's begin with the MockVitalsView. In our previous example, MockVitalsView didn't derive from any base class. To make our lives easier, we changed it to derive from DotNetMock.MockObject. The MockObject class gives us a stock implementation of Verify that does all the work for us. It does this by using expectation classes through which we indicate what we expect to happen to our mock object. In this case our tests are expecting specific values for the ErrorMessage property. This property is a string, so we add an ExpectationString member to our mock object. Then we implement the SetExpectedErrorMessage method and the ErrorMessage property to use this object. When we call Verify in our test code, the MockObject base class will check this expectation and identify anything that doesn't happen as expected. Pretty cool, eh? The other class that changed was our VitalsController class. Because this is where all the working code resides, we expected there to be quite a few changes here. Basically, we implemented the core logic of the view in the OnOk method. We use the accessor methods defined in the view to read the input values, and if an error occurs, we use the ErrorMessage property to write out an appropriate message. So we're done, right? Not quite. At this point, all we have is a working test of a controller using a mock view. We don't have anything to show the customer! What we need to do is use this controller with a real implementation of a view. How do we do that? The first thing we need to do is extract an interface from MockVitalsView. A quick look at VitalsController and VitalsControllerTests shows us that the following interface will work.

public interface IVitalsView
{
  string Name { get; set; }
  string SSN { get; set; }
  string ErrorMessage { get; set; }
}

After creating the new interface, we change all references to MockVitalsView to IVitalsView in the controller and we add IVitalsView to the inheritance chain of MockVitalsView. And, of course, after performing this refactoring job we run our tests again. Assuming everything is fine, we can create our new view. For this example I will be creating an ASP.NET page to act as the view, but you could just as easily create a Windows Form. Here is the .ASPX file:

<%@ Page language="c#" Codebehind="VitalsView.aspx.cs" 
  AutoEventWireup="false" 
  Inherits="UnitTestingExamples.VitalsView" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 

<html>
  <head>
    <title>VitalsView</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name=vs_defaultClientScript content="JavaScript">
    <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
  </head>
  <body MS_POSITIONING="GridLayout">
    <form id="VitalsView" method="post" runat="server">
      <table border="0">
        <tr>
          <td>Name:</td>
          <td><asp:Textbox runat=server id=nameTextbox /></td>
        </tr>
        <tr>
          <td>SSN:</td>
          <td><asp:Textbox runat=server id=ssnTextbox /></td>
        </tr>
        <tr>
          <td> </td>
          <td><asp:Label runat=server id=errorMessageLabel /></td>
        </tr>
        <tr>
          <td> </td>
          <td><asp:Button runat=server id=okButton Text="OK" /></td>
        </tr>
      </table>
    </form>
  </body>
</html>

And here is the code-behind file:

using System;
using System.Web.UI.WebControls;
using UnitTestingExamples.Library;

namespace UnitTestingExamples
{
  /// <summary>
  /// Summary description for VitalsView.
  /// </summary>
  public class VitalsView : System.Web.UI.Page, IVitalsView
  {
    protected TextBox nameTextbox;
    protected TextBox ssnTextbox;
    protected Label errorMessageLabel;
    protected Button okButton;

    private VitalsController _controller;

    private void Page_Load(object sender, System.EventArgs e)
    {
      _controller = new VitalsController(this);
    }

    private void OkButton_Click( object sender, System.EventArgs e )
    {
      if( _controller.OnOk() == true )
        Response.Redirect("ThankYou.aspx");
    }

    #region IVitalsView Implementation

    public string Name
    {
      get { return nameTextbox.Text; }
      set { nameTextbox.Text = value; }
    }

    public string SSN
    {
      get { return ssnTextbox.Text; }
      set { ssnTextbox.Text = value; }
    }

    public string ErrorMessage
    {
      get { return errorMessageLabel.Text; }
      set { errorMessageLabel.Text = value; }
    }

    #endregion

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
      base.OnInit(e);
    }
    
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {    
      this.Load += new System.EventHandler(this.Page_Load);
      okButton.Click += new System.EventHandler( this.OkButton_Click );
    }
    #endregion
  }
}

As you can see, the only code in the view is code that ties the IVitalsView interface to the ASP.NET Web Controls and a couple of lines to create the controller and call its methods. Views like this are easy to implement. Also, because all of the real code is in the controller, we can feel confident that we are rigorously testing our code.

Conclusion

Test-driven development is a powerful technique that you can use today to improve the quality of your code. It forces you to think carefully about the design of your code, and is ensures that all of your code is tested. Without adequate unit tests, refactoring existing code is next to impossible. Very few people who take the plunge into TDD later decide to stop doing it. Try and you will see that it is a Good Thing.

More Info on the Web

NUnit
http://www.nunit.org/
csUnit
http://www.csunit.org/ (an alternative to NUnit)
DotNetMock
http://sourceforge.net/projects/dotnetmock/
MockObjects
http://www.mockobjects.com/
The Humble Dialog Box
http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf

MFC中解决回车和ESC关闭的问题,重载OnOk(),OnCancel()函数的正确做法

本文参考了如下文章: http://msdn.microsoft.com/en-us/library/66b3y2ab(VS.71).aspx http://topic.csdn.net/u/2010...
  • phenixyf
  • phenixyf
  • 2014年12月12日 17:42
  • 1756

asp.net中给TextBox文本框添加水印,不影响正常使用

具体代码如下: 填写备忘录信息 function watermark(id, value) { var obj = document.ge...
  • yangmingxing980
  • yangmingxing980
  • 2014年03月24日 11:19
  • 1266

easy-ui中,判断textbox输入的为指定手机号码或者电话号码的JS

1、第一步 //自定义验证手机号 $.extend($.fn.validatebox.defaults.rules, { phoneRex: { validator: function...
  • BluewineY
  • BluewineY
  • 2016年11月11日 14:27
  • 1376

VB文本框textbox的那点事

1、限制文本框中只允许输入数字 在textbox的keypress事件里面写上 (1)判断输入的数字是否为小数 IfkeyAscii=46 and not(InStr(txtnumber,"."...
  • IstarI
  • IstarI
  • 2015年08月10日 10:43
  • 1804

C# textBox用法总结 [持续更新]

textBox用法总结: 1 去掉边框 【注:this = textBox】 this.BorderStyle = System.Windows.Forms.BorderStyle.None; 2 设...
  • taoerit
  • taoerit
  • 2015年01月08日 12:57
  • 5997

C#之WinForm基础 不改变原有的,向textbox中追加新的内容

慈心积善融学习,技术愿为有情学。善心速造多好事,前人栽树后乘凉。我今于此写经验,愿见文者得启发。 1、UI 2、代码 using System; using Sy...
  • yushaopu
  • yushaopu
  • 2016年09月21日 21:54
  • 1994

WPF教程(十七)TextBox

文本框是WPF最基础的文本输入控件,允许终端用户编写文本,可以是一行文字,也可以是多行。 单行文本框 文本框是如此的简单,你都不需要设置任何属性,就可以拥有一个完整的可编辑区。 ...
  • seanbei
  • seanbei
  • 2016年10月17日 22:16
  • 2002

Winform 验证输入TextBox身份证号是否有效

private void btnView_Click(object sender, EventArgs e) { string id = txtID.Text....
  • h0814
  • h0814
  • 2014年01月04日 01:07
  • 1021

Wpf中通过绑定来更新textbox的值

wpf中要动态的改变textbox的值需要通过绑定来实现,下面我就一步一步讲解如何绑定。 首先在MainWindow中定义了两个控件,一个button和一个textbox。并将这两个控件放在view...
  • jeryjeryjery
  • jeryjeryjery
  • 2017年04月17日 21:24
  • 3126

C# TextBox增加Padding屬性,或者TextBox垂直居中

public partial class PubTextBox : TextBox     {         //设置Rect消息         private const int EM_SETR...
  • losedguest
  • losedguest
  • 2017年03月08日 15:39
  • 1788
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Test-Driven Development in .NET摘要
举报原因:
原因补充:

(最多只允许输入30个字)