Fork me on GitHub
.Net TDD我用Machine.Specification

昨天碰巧看到Professional ASP.NET MVC 2这本书里面在介绍如何使用TDD进行开发,里面有这样一段代码,

 

1 public void Index() {
2 // Arrange
3   HomeController controller = new HomeController();
4
5 // Act
6   ViewResult result = controller.Index() as ViewResult;
7
8 // Assert
9   ViewDataDictionary viewData = result.ViewData;
10 Assert.AreEqual("Welcome to ASP.MET MVC!", viewData["Message"]);
11 }

 

 

这段代码让我意识到自己在项目中使用Machine.Specification这个TDD的测试框架的一些优点,跟大家分享。如果使用Machine.Specification, 上面这段代码可以可以这样来写:

 

1 [Subject(typeof(HomeController))]
2  public class When_getting_index_page
3 {
4 static HomeController controller;
5 static ViewResult result;
6 static ViewDataDictionary viewData;
7
8 Establish context =
9 () =>
10 {
11 controller = new HomeController();
12 result = controller.Index() as ViewResult;
13 };
14
15 Because of =
16 () => viewData = result.ViewData;
17
18 It should_have_the_welcome_message =
19 () => viewData["Message"].ShouldEqual("Welcome to ASP.MET MVC!");
20 }

 

 

  从行数上来讲使用Machine.Specifications是长了一些,但是带来的好处是不需要在代码里有注释,但同时阅读代码的人可以一目了然这个测试是在什么样的context下,because of 怎样的一个操作,should生成什么样的结果.

 

  Machine.Specification除了有ShouldEqual这个extention method之外, 它还提供了很多其它有用的extention method供你在不同的情况下使用, 比如, ShouldBe, ShouldBeNull, ShouldBeOfType, ShouldBeTheSameAs, ShouldEqual, ShouldNotBeNull, ShouldNotBeOfType, ShouldNOtBeTheSameAd, ShouldEqual.

 

  Machine.Specification还有一个不错的功能就是支持Behavior. 比方说, 你有好几个测试都需要测一些共同的功能, 这时你可以把这些共同的功能提出来放到Behavior中, 注意尖括号里面的内容是下面有[Behaviors]属性类的名称.

 

1 Behaves_like<When_preparing_article_add_edit_view_model_behavior> preparing_view_model;

 

 

 

1 [Behaviors]
2 public class When_preparing_article_add_edit_view_model_behavior
3 {
4 protected static IArticleAddEditViewModel model;
5
6 It should_set_the_periodicals =
7 () => model.Periodicals.ShouldNotBeNull();
8
9 // more assertions here
10   }

 

 

  以上两个例子只是对Machine.Specifications使用比较简短的一个介绍, 如果大家感兴趣的话, 可以到github上下载来试试看, 希望你会喜欢这个TDD测试框架. 再给两个连接, 是英文的对Machine.Specification的介绍, 其中一篇讲到如何配置Resharper, 如果你使用Resharper, 在每个测试的旁边会有一个绿色的小圆点, 点击后可单独运行这个测试.

1. Step by Step to Using MSpec (Machine.Specifications) with ReSharper

2. Introducing Machine.Specifications (or MSpec for short)

posted on 2010-11-17 22:45  HackerVirus  阅读(208)  评论(0编辑  收藏  举报