开发者

Unit Testing ASP.NET MVC3 Applications (with NHibernate)

I'm just starting my first MVC3 application, and I'm not sure how to unit-test it. I was planning to break out helper classes (static helpers, 开发者_运维百科usually) into a separate assembly, as well as model classes, so that I could test them with NUnit.

So I'm OK on helper classes; but how do I test model classes (considering that they're annotated for NHibernate and tied to the database), and how can I test my views and controllers?

What are the specific tools and techniques I need to test NHibernate-bound models, as well as ASP.NET views and controllers? I'm not sure. NUnit only solves some of the problem.

Edit: Here's some samples of code -- I'm not on my dev machine right now, so I don't have real code to show-case.

  • Models: Anything from the ActiveRecord documentation
  • Controllers: The standard HomeController from the MVC3 documentation
  • Views: Any strongly-typed view (let's say Create) generated from the right-click context menu (Add > View)

Specific questions:

  • How I can test saving models without actually saving to the main/production database
  • Scope for testing views; should I simply test fields exist? What about validation error messages?
  • Controllers: scope for testing. Should I test that actions touch and deform database data as expected (eg. /get/id gets that object; /delete/id deletes that object)?


You can get there by various kinds of tests, but you need to apply them wisely depending on what you are going to test:

  • Use unit test to test your controllers, or your business logic, without hitting the database.

  • Use integration testing by running on an in-memory database (which NHibernate supports and is easy to setup). You can make sure a scenario actually works, e.g. using a valid scenario, all the business logic is working, your controller pass the data to persistence mechanism and it goes correctly into the database.

  • You can use UI Testing using frameworks such as Selenium but only do that where really needed, because it is not easy as two previous types of tests, and would become hard to maintain and fragile.

It is a best practice to keep your view (UI) thin, and test other layers behind the UI, as testing the UI probably does not worth all the hassle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜