Test-Driven Development in .NET摘要

本文介绍了.NET中的测试驱动开发。使用模拟对象确保单元测试只针对目标代码,避免测试其他类代码。业务层类应松耦合、高内聚,便于创建单元测试。对于用户界面,可分离逻辑与视图,通过接口和控制器实现自动化单元测试。测试驱动开发能提升代码质量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值