How to implement unit tests in a database-backed ASP.NET application (also UI testing) - asp.net

ASP.NET apps that I've developed (on ASP.NET 2.0) have typically been backed by a database; the great majority of the .NET code on the server loads data in the form of a DataSet or SqlDataReader and uses it to databind something like a DataGrid. The meaningful logic is either database dependent or user interface dependent.
In this context, how should I implement unit tests that would be run by a continuous integration server (probably CruiseControl.NET)? Should I set up a test database connection for it to use to test CRUD operations and more complex SPROCs, or should more logic be contained in the .NET code and not in a SPROC? This becomes more complex when there is structure in the database that the application expects to find (such as a Users table in something I'm writing for a CMS).
Also, what are the best ways to do unit-testing of user interfaces? I've found NUnitASP, which is now abandoned but mentions Selenium and Watir.

Take a look at the MVP pattern (Model View Presenter). This should allow you to isolate the behaviour of your system and unit test it properly.
Also, consider switching to MVC (I would go with Fubu over ASP.NET MVC). This will allow you to test controllers and have a more rails-like experience.
To automate, I use WatiN (like watir but for .NET). On top of it I use StoryTeller (Google "StoryTeller Jeremy Miller") to present what is happening in a more human readable way and to provide templates for QA to use.
I would highly recommend against any business logic in sprocs. Stay away from them. Look at the repository pattern to abstract away getting and setting data.
Hope this gets you started.

Related

Make a .Net DLL Thread-safe for Web App Consumption?

I've written a class in VB.Net that is consumed in an ASP.NET Web Application running IIS7. I use .NET Framework 4.0. The class performs a REST request to an online and retrieves an XML response containing strongly typed data.
This class also performs caching using an SQL Server database. The class is compiled to a .DLL and referenced by the Web Application. It works excellent and now I need to know how to make the class thread-safe.
I have no experience with making code 'thread-safe'. I don't know where to begin in determining whether or not it is thread-safe. Am assuming, because I didn't pay attention to this during development, that it is NOT thread-safe and that since it the web application will be used by many users at the same time that it must be payed attention to.
Can anyone point me on how to test for thread-safety? Are there any resources online that that will give me some ideas? Are there any rules of thumb that will tip me off as to where my main concerns are?
The easiest possible thing you can look out for is the use of "static" (C#) or "Shared" (VB.NET) variables. If these variables can be modified throughout the lifetime of the application you will likely run into threading issues which can really often result in "random looking" problems.
I would also be concerned about how you are doing the caching in your database as multiple .NET threads hitting SQL (for the cache) could cause issues as well depending on how its designed.
Bottom line is you are likely going to need to learn more about threading if you want to be sure this is going to not have issues. Probably the best book I have ever read in terms of simple to very complex C# topics is C# 4.0 In a Nutshell I would take a look at that book especially the threading chapters. (Seriously read the whole thing though) If you get that read through and have a good understanding of the concepts mentioned you should be fine.

SpecFlow, Webdriver and Mocks - is it possible?

The question in short is that we are stumbling upon BDD definitions that more or less require different states - which leads to the necessity for a mock of sorts for ASP.NET/MVC - I know of none, which is why I ask here
Details:
We are developing a project in ASP.NET (MVC3/Razor engine) and are using SpecFlow to drive our development.
We quite often stumble into situations where we need the webpage under test to perform in a certain manner so that we can verify the behavior, i.e:
Scenario: Should render alternatively when backend system is down
Given that the backend system is down
And there are no channels for the page to display
When I inspect the webpage under test
Then the page renderes an alternative html indicating that there is a problem
For a unit test, this is less of an issue - run mock on the controller bit, and verify that it delivers the correct results, however, for a SpecFlow test, this is more or less requiring alternate configurations.
So it is possible at all, or - are there some known software patterns for developing webpages using BDD that I've missed?
Even when using SpecFlow, you can still use a mocking framework. What I would do is use the [BeforeScenario] attribute to set up the mocks for the test e.g.
[BeforeScenario]
public void BeforeShouldRenderAlternatively()
{
// Do mock setups.
}
This SO question might come in handy for you also.
You could use Deleporter
Deleporter is a little .NET library that teleports arbitrary delegates into an ASP.NET application in some other process (e.g., hosted in IIS) and runs them there.
It lets you delve into a remote ASP.NET application’s internals without any special cooperation from the remote app, and then you can do any of the following:
Cross-process mocking, by combining it with any mocking tool. For example, you could inject a temporary mock database or simulate the passing of time (e.g., if your integration tests want to specify what happens after 30 days or whatever)
Test different configurations, by writing to static properties in the remote ASP.NET appdomain or using the ConfigurationManager API to edit its entries.
Run teardown or cleanup logic such as flushing caches. For example, recently I needed to restore a SQL database to a known state after each test in the suite. The trouble was that ASP.NET connection pool was still holding open connections on the old database, causing connection errors. I resolved this easily by using Deleporter to issue a SqlConnection.ClearAllPools() command in the remote appdomain – the ASP.NET app under test didn’t need to know anything about it.

Putting a new web interface on an old fat-client database

My company has a fairly old fat client application written in Delphi. We are very interested in replacing it with a shiny new web application. This will make maintenance a breeze and many clients want a web application.
The application is extremely rich in domain knowledge, some of which is out of our control. Our clients use the program to manage their own clients and report them to the government. So an inaccurate program is a pretty big thing. The old program has no tests. We are not sure yet if we will implement automated testing with the new one.
We first planned to basically start from scratch. But we are short handed and wanting to basically get everyone on the web as soon as possible. So instead of starting from scratch we've decided to try to make use of the legacy fat-client database.
The database is SQL Server and can be used in SQL Server 2008 easily. It is very rich in stored procedures, functions, a few triggers, and lots of tables with over 80 columns... But it is decently normalized. We want for both the web application and fat client to be capable of using the same database. This is so that if something breaks badly in the web application, our clients can still use the fat client and connect to our servers. After the web application is considered "stable", we'd deprecate the fat client.
Has anyone else done this? What tips can you give? We want to, after getting everyone on the website, to slowly change the database structure to take care of some design deficiencies. What is the best way to keep this in a data access layer so that later changes are easy?
And what about actually making the screens? Is there any way easier than just rewriting an 80 field form in ASP.Net? Are there any tools that can make this easier?
The current plan is to use ASP.Net WebForms (.Net 3.5). I'd really like to use MVC, but no one on the team knows it including me.
We are not sure yet if we will implement automated testing with the
new one.
Implement automated testing. What's the point in replacing one buggy program with another?
Good question, but "Slowly change" the db structure after getting everyone on the website, sounds like a joke...
I would rather take the opportunity to create a fresh db structure, write a bulletproof migration script for you db, that you can try out and rewrite a zillion times without any side effect fro your clients, and then write whaterver you want (fat/web) on the new db, have it tested and migrate everyone when it's ready.
I have a couple suggestions:
1) create a service layer to abstract away the dependance on the DAL. In a situation as you describe having a layer of indirection for the UI and BLL to rely on makes DB changes much safer.
2) Create automated tests (both unit and integration), especially if you plan on making fairly significant changes to the Domain or Persistance layers (BLL/DAL). To make this really easy you should always try to program to an interface. This makes your code more flexible as well as letting you use mocking frameworks (Moq is one I like) to ensure your tests truely are unit tests and not integration tests.
3) Take a look at DDD (http://domaindrivendesign.org/) as it seems to fit pretty well with the given scenario. At the very least there are some very useful patterns that can help make your application more flexible.
4) MVC isnt very hard to learn at all, it is however an easy way to get unit testing setup for the UI as a result of the MVC architecture (testing the controller and not the view). That said, there is no reason you couldn't unit test web forms, its just a bit more work. MVC really is just a UI framework/design pattern (more Model2 but we can ignore that for now). It gets you closer to the metal so to speak as you will be writting a lot more HTML and using a Model (the 'M') for passing data around.
For DDD take a look at Eric Evans book: http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=sr_1_1?s=books&ie=UTF8&qid=1317333430&sr=1-1
Hope that helps
ASP.NEt forms is a no starter, is completely inappropriate for something like this. I recommend to start with something like Creating an OData API for StackOverflow including XML and JSON in 30 minutes, then build your Web app on top of that (ie. push it to the client, use JQuery/Silverlight).

Refactoring a legacy WebForms app to better separation of concerns

i.e. Is MVP still the next best choice when MVC is not an option?
I thought I'd ask this here as I'm sure there are others like me who don't have the luxury of being on a green-field project and want to refactor a webforms UI to better separation of presentation from business objects...
I'm working on a legacy application tasked with adding relatively small additional requirements, enhancements, and bug fixes.
The part of the application I'm addressing here may be characterised as the UI for a set of CRUD operations over business objects that are persisted to a relational database.
The existing UI uses a MultiView control to navigate between the editing of associated business objects (one-one associations or one-many / parent-child). Yes, that's right - all on one page. Unfortunately there is very sparing use of UserControls so the markup and code-behind is hundreds of lines long.
On each View a FormView manages the CRUD over the business objects via various ObjectDataSources. Within the ItemTemplate of each FormView various server controls databind to fields or methods on an ObjectDataSource.
I'd like to introduce more separation of concerns and get some of the reams of code out of Page code-behind.
My research so far suggests to me that I might consider:
Use a flavour of Model View Presenter; more specifically - use an ObjectContainerDataSource from the Web Client Software Factory to make it easier to bridge between the current UI and a set of new Presenter classes.
Build again from scratch with an MVC framework (not an option).
Leave well alone; an MVP pattern is only justified if I need to re-use my Presentation in different UI scenarios?
If I settle with (3) I'd still like to know how to start refactoring towards better separation of presentation.
What would you do? any other ideas gratefully received...
Here's some more background for anyone who's interested:
The domain is in pharmaceutical research but that's fairly irrelevant and you can think of it as pretty typical line-of-business - user configuration of a family of settings that form the operating conditions of another part of the application.
The business object layer has already been built in a very consistent manner. Although I may not like it, I can't neccesarily justify changing it. Each object is it's own Repository / Data Access Object in that there are static methods for 'get by ID' and 'get list by criterion'. Where possible common operations are implemented in an abstract base class. Each business object delegates the data access work to a Data Access Layer that makes use of ADO.NET 2.0 Provider Factory mechanisms to remain relatively abstracted from a concrete Provider. In this respect it shares a lot in common with any app that uses the Data Access Application Block from the Microsoft Enterprise Library.
There are fairly exhaustive integration tests written in NUnit that set up a test database from scratch so they take ages to run but at least they verify that stuff works as it should (at some point in the past anyway ;-). There is almost no true unit testing in place (yet).
WebForms now has an emerging effort in the form of the ASP.NET Web Forms MVP project
"...there are still a host of
compelling advantages to ASP.NET Web
Forms.
The ASP.NET Web Forms MVP project is
... an approach that facilitates
separation of concerns and testability
whilst maintaining the rapid
development that Web Forms was built
to deliver"
Rob Conery has concerns that this may be a wasted effort and an unneccesary distraction now that we have MVC but at this stage I still think the source code is worth a look...
http://haacked.com/archive/2006/08/09/ASP.NETSupervisingControllerModelViewPresenterFromSchematicToUnitTestsToCode.aspx has a good example of doing MVP with webforms. The advantage is not just that your UI is decoupled from BL - the real treat is that you can write tests for the code.

Best Small & Mid-Size Application Arcitecture

I am Developing a mid-size application and want to implement Application Architecture, I've read some Architecture Books and Approach and think about
AAFN (Application Arcitecture For .net) presented by Microsoft
SOA
SDLM
SDO
MVC
and vice versa ...
this is a web application that will extended with some other small application ( just think about something like a M.I.S with a (or two) core)
Whitch Projects I should have I think about
Common // to use in all projects
Framework // main framework
DAO // data access object ( entityframework or nHibernate )
UI // will available in 2 variant web and windows(wpf) interface )
BusinessEntities // all subApplication project logic will goes there
ApplicationNameProject // each application have their Own Logic (in BussinessEntities)
ApplicationUnit // each application Entity will place here
ApplicationNameProject // each application data Entity (in Application Unit)
Services // WCF Services goes here to contribute with all applications
this is the architecture witch I think about, I do not have any force to use this, I want to know whats the best fit for me, can Change all of it or add some other projects and remove these projects
any help appriciated
There is no "best small or mid-size application architecture" as a silver bullet to fit any project, so drop that idea right now or you'll be in for a world of pain down the road.
The architecture for any given project will fit the purpose of that project. In some cases, ASP.NET WebForms with a direct queries into the database will be the most appropriate architecture, in some cases MVC will be the right architecture, in some cases a windows forms application built on top of a web service that connects to a relational database through an ORM like LINQ-to-SQL or NHibernate.
You can't decide on a one-architecture-fits-all approach, it just doesn't work. Each architecture has its merits and weaknesses and thus projects for which it is well suited and projects for which it should be avoided. You should pick the approach that makes the most sense for the current project/scenario.
Given that however, I tend to take a fairly uniform approach.
If I need a quick utility project that does a very specific thing and is highly unlikely to be needed for anything else, I might use a console application with queries against my database hardcoded.
If I need a common set of queries that I'm likely to need from multiple projects, I'll write them as stored procedures to get the performance benefits and build a data access layer that will leverage these stored procedures to give me standardized business objects, in a standard DAL (data access layer)/BOL (business object layer)/BLL (business logic layer) approach. This is advantageous because it means that once I've got this set of libraries built I can float any application over the top - for instance a webforms or MVC application.
MVC is advantageous because of separation of concerns - your controller can interact with your business library simply to access the data it needs and your views are really just that - a view of the data that the user can interact with. The views do nothing more than take the current data view to the user and transport any data changes back from the user to the controller - no logic is held in the view and as such it means that it's far easier to unit test and make changes to components without affecting the rest of the application.
The drawback to a multi-tiered or multi-layered approach like this though is that it takes time to architect it properly and if you're only after a throw-away utility application like they demonstrate on stage at developer conferences then this is complete overkill and I wouldn't bother with it.
Think of it like this: Every layer, every library, every component requires justification. If there is less justification for than against, then don't do it. The key is not to do something without reason - anything you do is correct providing that you have a well thought out reason for it, and by well thought out, I mean that you've found very good reasons for and against and you've made an educated decision, you've not made a decision based on half thoughts, or worse, no thought at all.
Anything but the most trivial .NET application should have several projects: a UI layer, some kind of business logic layer, a persistence (storage) layer and accompanying test projects. Each project should interact loosely through interfaces.
In general you should create the minimum number of layers you need to make your code testable and easy to understand.
To figure out what the minimum is that you need it can be a good idea to let your tests drive the internal design of the system. Each layer should have tests in its own right, with (possibly) the exception of the top HTML layer and the bottom SQL layer.
With that in mind it helps to separate concerns as far as possible. For example SQL queries should almost never be in the same block of code as HTML support: split things into multiple layers that each do one and only one thing. This makes changes easier.
Be aware of the difference between systems architecture (where loosely coupled Web services using e.g. REST interact) and the internal design of the system. It's a good idea to decouple the Web service interfaces (as consumer or provider) in their own layers as this is an area that often changes.
These designs are an art that's best learned by practice. With good unit tests you should find refactoring an application design fairly swift, so it's a good idea to look at technologies like Spring.NET or other inversion of control containers to make this easy.

Resources