Unit Test The Presentation Layer Of A Web Forms Application?
Jan 8, 2011
What is the best way to unit test the presentation layer of a web forms application? I have been told that there are frameworks available like Watin. Are there better tools around?
I am new to this .NET what is the difference between N-Tier and 3- Tier Architecture. If they are same. How to pass the values from presentation layer to business logic layer.
For Example
I have 10 controls in presentation layer. I passing values to these controls. How the architecture works.
I've even got my JQuery Ajax submission going on now but I've encountered another problem. I *think* it's something to do with the structure I'm using but like I say, I'm fairly newo this.I have my AJAX form submission which builds my "PersonViewModel" (model for the presentation layer) in JSON and sends it to "@Url.Action("RegisterSubmit")" in my Person Controller. Now, I seperate my business layer from my View/presentation layer so in "RegisterSubmit"I'm verifying the model is valid then instantiating a new instance of my business model "Person", adding the values from "PersonViewModel" and then calling my "Save" function.
This is my first test for Asp.Net Web Application. We have an Engine consisting of several modules. I need to test classes in Engine Module. Though these clases are part of Asp.Net App, they consists of only business logic. How can I test these classes in isolation other being part of WebApp ? because i am getting this error
The Web request 'http://localhost:8936/' completed successfully without running the test. This can occur when configuring the Web application for testing fails (an ASP.NET server error occurs when processing the request), or when no ASP.NET page is executed (the URL may point to an HTML page, a Web service, or a directory listing). Running tests in ASP.NET requires the URL to resolve to an ASP.NET page and for the page to execute properly up to the Load event. The response from the request is stored in the file 'WebRequestResponse_BlogManagerBPOConstr.html' with the test results; typically this file can be opened with a Web browser to view its contents.
Actually what i am doing in my Data Access Layer dragging store procedure to TestDbml to display records and creating data context instance in BAL to retrieve records and my method in BAL is like this
public IEnumerable display() { using (TestDataContext db = new TestDataContext()) { var display = obj.USP_Actor_View_Speciality(p_UserName, 1); return display as IEnumerable; }
Now the problem is that how can i iterate or fetch over the records and display accordingly in my Presentation Layer so that i could return all the field parameteres Like ield1=val.field1,field2=val.field2.
I'm using VSTS 2K8 and I've set up a Unit Test Project. In it, I have a test class with a method that does a simple assertion. I'm using an Excel 2007 spreadsheet as my data source.
My test method looks like this:
[Code]....
As indicated in the method decoration attributes, my Excel spreadsheet is on my local C:/ Drive. In it, the sheet where all of my data is located is named "Sheet1".I've copied the Excel spreadsheet into my project and I've set its Build Action = "Content" and I've set its Copy to Output Directory = "Copy if Newer".
When trying to run this simple unit test, I receive the following error:
The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: ERROR [42S02] [Microsoft][ODBC Excel Driver] The Microsoft Office Access database engine could not find the object 'Sheet1'. Make sure the object exists and that you spell its name and the path name correctly.
I've verified that the sheet name is spelled correctly (i.e. Sheet1) and I've verified that my data sources are set correctly.Web searches haven't turned up much at all. [Code]....
We are designing a system that has functionality that is essentially the same at the presentation layer and the exposed API layer. My question is what technique / strategy to use so we can get the most reuse out of our code with performance in mind? Here's a simplified example: A user can add a Customer via a web form. This will fire the Customer.Create() method. An API consumer / user can add a Customer via a SOAP / HTTP-POST to a web service which will call the Customer.Create() method.
Imagine these layers: PRESENTATION | | WEB SERVICE API (Customer.Create() is available here | | FACADE Business Object Interface - Customer.Create() signature is here | | BUSINESS Business object - Customer.Create method() is fleshed out here | | DATA ACCESS - Writes data
The presentation layer SOAP calls the Create() web method, which calls the facade's Create() method which calls the business object's Create() method which wires via the data access layer.
Questions:
Is there a concern about performance in using the API's web services in our presentation layer, or are there alternatives to connect the presentation layer directly to the facade? If so, what technology to use (WCF, Remoting, Web Services, etc)?
I creating 3 tier arch wpp in VS 2010. I added the BusinessAccessLayer refernce in Presentation Layer. and I created DataAccessLayer[DAL] and ORM [DBModel.DBML]. when i try to create the instance for the Table in presenation layer[default.aspx], The Table name is not shown.After adding the DataAccessLayer refernce in the presentation layer, the table name[MM_User] instance are shown.Is it the right method [Adding the DAL refernce in Presenation Layer]? If not, whats the solution for for accessing the instance of the tables[MM_User].Is it related to the Creating the DataContextWrapper class in DAL?
In an ASP.NET MVC3 environnement with entity framework. Should the Unit of Work point to the service layer or the repository (and then the repository point to the service layer) ?
Ive saw two example:
* One where the unit of work and repository both have an instance to the service layer..
Link: Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable
Doesn't use a service layer but its obvious that one could be use in that case.
* Second where the unit of work have an instance to the repository which have an instance to the service layer..
I'm trying to unit test the MembershipProvider, however I cant figure out how or whether there is any need for unit testing of it...
My business layer:
public interface IAccountService { MembershipCreateStatus CreateUser(string userName, string password, string email); } public class AccountService : IAccountService { private readonly MembershipProvider provider; public AccountService() : this(null) { } public AccountService(MembershipProvider providera) { this.provider = providera ?? Membership.Provider; } public MembershipCreateStatus CreateUser(string userName, string password, string email) { if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", userName); if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", password); if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", email); MembershipCreateStatus status; provider.CreateUser(userName, password, email, null, null, true, null, out status); return status; } }
The only examples I've found so far requires a "MockMembershipProvider" with a local database setup... seems quite odd to me.
I want to test that when my form data is posted back to my controllers that the data annotations and the model binding is going to do its job and give the correct model state. After googling for a while I can't find a really good tutorial or article that shows how to do this.
Can anyone point me in the right direction? What is the best practice in this area? I have read that I may need to use moq and MVCContrib but I have not read a tutorial that makes me shout, "Yes, this is the right way to do it!"
I am doing Automated coded ui testing in asp.net 2010 for web application. I am testing site and i need to know how can i create the test which will work with all browsers. Right now i created test in IE 8 but its not working in Firefox. So is there any way i can create one test and will work in all browser.
We are using a tierd design with a Data Access Layer and classes for everything we need. This serves as an advantage because we do not have to write querys over and we can separate the Presentation layer from the Data Access Layer and Business Rules.I have always in the past populated GridViews, DataLists, repeaters,etc with SqlDataSources. This is what I have become accustomed to and I feel like it is simple. For querys such as Select * from Members, I feel like using a DataSource is simpler than having to go in the code and calling methods to populate and DataBind these presentation controls.
I am working with a gentleman who has introduced me to the world of Data Access Layers and we are breaking everything down into simeple, but effective queries to populate controls and do what we need to accomplish with this application. He is not very approving of using any type of DataSource. We are disagreeing on the time and place to use these class methods to call the database.So my question is, which is more widely used in the programming world? Do most people use DataSources to populate presentation controls regardless of the Data Access Layer they are working with? Which type of queries are best suited for a DAL - simple, populating queries or complicated joins and upserts?
I want to mock ASP.NET 3.5 behavior in order to unit test my WebControls: I want to test how they perform with mock data with existing system of events. Basically I want to test generated result HTML based on input mock data. How to do it? I looked into NMock, but it doesn't suit my needs for 2 reasons:
It just runs ASP.NET server in separate process in order to get resulting HTML; My WebControls output HTML as a text on render, so there are elements which do not correspond to any ASP.NET control (except LiteralControl in some cases). Also, I have huge legacy system, so rewriting everything for MVC won't work for me (too much job), I need to write unit tests to existing controls.
I just started my first MVC 2 project in VS 2010. I decided to start the debugger, just to see the default controllers in action, and have received several of the following kinds of errors for the test unit project:
Error 1 The type or namespace name 'Controllers' does not exist in the namespace 'MajorProductions' (are you missing an assembly reference?) c:userskevindocumentsvisual studio 2010ProjectsMajorProductionsMajorProductions.TestsControllersHomeControllerTest.cs 8 24 MajorProductions.Tests
From what I can see, however, MajorProductions.Controllers does exist, as it's created by default in my regular/non-test project.The unit test code in question is:
[Code]....
And the error is being triggered by the using MajorProductions.Controllers line. I have similar errors elsewhere in my unit test project, so I figure if I can fix this, I can fix the others.
We wanted to upgrade our projects from ASP.NET MVC 2 to 3. Most of our tests succeeded, but there are some that fail on ValueProviderFactories.Factories.GetValueProvider(context).
Here is a simple test class that ilustrates the problem.
[TestFixture] public class FailingTest { [Test] public void Test() { var type = typeof(string); // any controller AuthenticationController c = new AuthenticationController(); var httpContext = new Mock<HttpContextBase>(); var context = c.ControllerContext = new ControllerContext(httpContext.Object, new RouteData(), c);
I created a little web service to minify JavaScript, and everything was nice, with all my tests passing. Then I noticed a bug: if I tried to minify alert('<script>');, it would throw a HttpRequestValidationException.
So that's easy enough to fix. I'll just add [AllowHtml] to my controller. But what would be a good way to unit test that this doesn't happen in the future?
The following was my first thought:
[TestMethod] public void Minify_DoesntChokeOnHtml() { try { using (var controller = ServiceLocator.Current.GetInstance<MinifyController>()) { return controller.Minify("alert('<script></script>');"); } } catch (HttpRequestValidationException) { Assert.Fail("Request validation prevented HTML from existing inside the JavaScript."); } }
However, this doesn't work since I am just getting a controller instance and running methods on it, instead of firing up the whole ASP.NET pipeline.
What would be a good unit test for this? Maybe reflector on the controller method to see if the [AllowHtml] attribute is present? That seems very structural, and unlikely to survive a refactoring; something functional might make more sense.
I have been spinning my wheels now for awhile trying to figure out how I can possibly unit test the following code. At first I was going to use Moq to mock everything, but it doesn't include the ability to mock sealed classes. I know I need to abstract out the calls to the implementation (Configuration) using an interface? but I can't seem to make it all work right. The code can be altered but I would prefer to keep the methods static, unless you can present a compelling reason not to. You can add interfaces or create whatever seams are needed. Also, GetConnStringByName() can be refactored to return the relevant string instead of a ConnectionStringSettings. Thoughts?
namespace Stackoverflow.Rocks { /// <summary> /// Utility class for progmattically selecting values from the Web.config file. /// </summary> public class WebConfigStrings { //private static Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); /// <summary> /// Retrieves the desired connection string value based upon the target name. /// </summary> /// <param name="connectionStringName">The target connection string referenced in the Web.Config</param> /// <returns>The value specified in the Web.Config by your connectionStringName</returns> public static ConnectionStringSettings GetConnStringByName(string connectionStringName) { Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); ConnectionStringSettings connString; connString = rootWebConfig.ConnectionStrings.ConnectionStrings[connectionStringName]; return connString; } /// <summary> /// Retrieves the desired application string value based upon the target name. /// </summary> /// <param name="applicationStringName">The target application string referenced in the Web.Config</param> /// <returns>The value specified in the Web.Config by your applicationStringName</returns> public static string GetAppStringByName(string applicationStringName) { string appString = ""; appString = ConfigurationManager.AppSettings[applicationStringName]; return appString; } } }
I'm trying to build my first MVC site and also write unit test for the first time. I can't figure how to write unit test for methods that take parameters. How do I write a test method for this controller action?
Since I upgraded from MVC 2 to MVC 3 RC, using TryUpdateModel causes a NullReferenceException. This problem only occurs when running my action method as part of a unit test. Running it on the actual server works as expected. Here's a stack trace of the exception:
System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext) at System.Web.Mvc.ValueProviderFactoryCollection.<>c_DisplayClassc.b_7(ValueProviderFactory factory) at System.Linq.Enumerable.WhereSelectEnumerableIterator[Code].... 2.MoveNext() at System.Collections.Generic.List[Code].... 1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) at System.Web.Mvc.Controller.TryUpdateModel[TModel](TModel model, String prefix) ... my own code from here on....
In case it matters, my controller has the following signature:
[Code]....
My guess is that this has to do with the new way DI works in MVC3, but I can't figure out what I'm doing wrong. Perhaps there is something in terms of DI setup that is required in MVC 3, but wasn't required in MVC 2?