Mock 3.5 To Unit Test Web Controls?

Feb 4, 2010

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.

View 1 Replies


Similar Messages:

Unit Testing - How To Mock A Model In MVC

Nov 11, 2010

I've made a custom model, and I want to mock it. I'm fairly new to MVC, and very new to unit testing. Most approaches I've seen create an interface for the class and then make a mock that implements the same interface. However I can't seem to get this to work when actually passing the interface into the View. Cue "simplified" example:

[code]...

Upon a HttpPost I get a "Cannot create an instance of an interface" exception. I seems that I can't have my cake (passing a model) and eat it (pass mock for unit testing). Maybe there's a better approach to unit testing models bound to views?

View 3 Replies

Creating A Mock URL Referrer In MVC For Unit Testing?

Feb 10, 2010

I'm currently testing my application and am stuck on trying to figure out how to create a custom fake URL referrer. I've tried to hard code it, but am getting an error that it is read-only. Here is what I've tried so far:

fakeController.HttpContext.Request.UrlReferrer.AbsolutePath = "http://www.yahoo.com";
as well as,
fakeController.Request.UrlReferrer = "http://www.yahoo.com";

I've searched the web for some ideas on how to create a fake/mock URL referrer for my fake controller, but have had no luck.

Note: I'm using Visual Studios built-in unit testing facilities.

UPDATE:

I would be more than willing to use any other unit testing system outside of Visual Studio, unfortunately here at my work we are only allowed to use Visual Studio's built-in system, so I gotta work with what I've got.

View 3 Replies

Unit Testing / Mocking HttpContext Without Using Any Mock Framework

Sep 7, 2010

Since I'm having problem with unit testing RenderPartialViewToString() with Moq framework [URL] I'm thinking about getting my controller directly, without using Moq for these particular test, however, how do I mocks (or set) the HttpContext for my test without using any Moq framework?

I need to able to do something similar to this, without Moq of course:

var mockHttpContext = new Mock<ControllerContext>();
mockHttpContext.SetupGet(p => p.HttpContext.User.Identity.Name).Returns("n1\test");
mockHttpContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);

View 2 Replies

Architecture :: Unit Testing Delegates With Mock Framework?

Apr 3, 2011

I'm using the mock framework to unit test some methods. I came across some methods that use delegates. I did not find a way to setup these delegates to return the objects that I want. The mock framework does not support it as far as I know. Is this supported in other mock frameworks like nMock?

View 3 Replies

Unit Testing Error - The Unit Test Adapter Failed To Connect To The Data Source Or To Read The Data

May 6, 2010

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]....

View 5 Replies

C# - Trying To Unit Test The MembershipProvider?

Nov 21, 2010

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.

View 1 Replies

How To Unit Test Mvc 2.0 Controllers The Right Way

Jan 9, 2011

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!"

View 1 Replies

How To Unit Test Webforms Applications

Jun 29, 2010

I'm looking for examples or some tutorials that explain how to Unit Test ASP.NET Webforms applications?

Can any one share that?

View 2 Replies

MVC :: 2 Errors With Unit Test Project?

Jul 10, 2010

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.

View 2 Replies

MVC :: Unit Test Razor View In 3?

Mar 11, 2011

Is it possible to write unit tests against razor view in MVC 3? If yes, can anyone point me to code sample to unit test a razor view in MVC 3?

View 2 Replies

How To Unit Test ValueProviderFactories In MVC3

Jan 5, 2011

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);

[Code]...

View 2 Replies

C# - Unit Test Configuration For Application?

Jan 12, 2010

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.

[Code]....

View 1 Replies

MVC :: Writing To TempData In Unit Test?

Apr 30, 2010

Some of my controller actions look for data in TempData. How can I insert data into TempData from my unit tests?

View 1 Replies

Unit Test For A View Attribute Using Moq?

Feb 19, 2010

I am using Moq for unit testing and I would like to test for a view's attribute.In this case the Authorize attribute.Example View Code:

[Authorize(Roles = "UserAdmin")]
public virtual ActionResult AddUser()
{

[code]...

View 2 Replies

How To Unit Test For Turning Off Request Validation

Dec 20, 2010

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.

View 1 Replies

C# - Unit Test This .Net Code - Refactoring Allowed?

Jan 7, 2011

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;
}
}
}

View 3 Replies

MVC :: Write Unit Test For Method With Parameter?

Oct 26, 2010

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?

[Code]....

View 2 Replies

MVC :: TryUpdateModel Throws NullReferenceException In 3 Unit Test

Nov 12, 2010

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?

View 6 Replies

C# - How To Unit Test A Website With No Backend Class

Feb 26, 2010

A friend suggested instead of having a backend class which verifies the user permission in every public function (results are cached and non static) i should have a more 'streamlined' site. When i dropped the backend i also drop the database code and merged them in the appropriate user permission (base user, logged_in_user, moderator).

The site code looks better now that merging them has decreased LOC (tons of LOC in fact) and i write Method() instead of backend.Method() which increases readability. However now that i have no backend how am i suppose to unit test my code? and what about things like user file upload with different extensions? (txt vs jpg vs FLAC)

View 4 Replies

C# - Unit Test Insert/update/delete?

Mar 18, 2010

I have googled this a little and didn't really find the answer I needed. I am working on a webpage in C# with SQL Server and LINQ for a customer.I want the users to be able to send messages to each other. So what I do is that I unit test this with data that actually goes into the database.The problem is that I now depend on having at least 2 users who I know the ID of. Furthermore I have to clean up after my self. This leads to rather large unit tests that test alot in one test. Lets say I would like to update a user. That would mean that I would have to ceate the user, update it, and then delete it. This a lot of assertions in one unit test and if it fails with updating i have to manually delete it. If I would do it any other way, without saving the data to DB, I would not for sure be able to know that the data was present in the database after updating etc.What is the proper way to do this without having a test that tests a lot of functionality in one test?

View 3 Replies

Visual Studio :: Unit Test For VWD2010 / MVC 2 On Windows 7?

Jun 6, 2010

I'd like to tryout ASP.NET MVC2, im using VWD2010 on Windows 7. I can't seem to be able to get the unit test dialog to pop up. I googled it and all I find is nUnit templates for VWD2008.

Anyone running into this issue with same setup as mine?

View 3 Replies

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?

View 1 Replies

Configuration :: Accessing Web Service In Dll From Unit Test Project?

May 25, 2010

I am not able to override the design-time URL of a webservice in my web config.

I must be doing something stupid

My Dll is called SMSLibrary2X which has a web reference to a UserService web service like this (taken from the app.config of the dll:

<setting name="SMSLibrary2x_TAMService_UserService" serializeAs="String">
<value>https://devss.ourdomain.ca:4452/UserService.asmx</value>
</setting>

, however, in the web reference, the URL property is [URL]

As I understand it, the app.config for the DLL is not really pertinent, except perhaps to copy the setting into the app.config of the unit test project.

So, In the SMSLibrary2xTests web.config file, I have this:

[Code]....

However when my unit tests run, always pick up the URL of the web service that I defined when I added the Web Reference to the SMSLibrary2x DLL project, which is fine for design time, but not appropriate when I want to point to different versions at deploy time (dev, QA, prod, etc). I just can't seem to get it to pick up the proper URL.

View 5 Replies

How To Create A Unit Test That Updates A Record Into Database

May 13, 2010

How do I create a unit test that updates a record into database in asp.net

View 1 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved