Unit Testing - Mocking HttpRequest In .NET 4.0 / HttpRequest Is Sealed With No Interface

Jul 15, 2010

I'm writing unit tests in ASP.NET 4.0 web application (ASP.NET Forms, not MVC). There are several spots in the code where I call the ServerVariables collection to call variables like REMOTE_ADDR. Since my unit tests do not actually initiate HttpRequests when executing my code, things like ServerVariables are Null and therefore error when I try to call HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")

All the solutions I've found to address this issue refer to MVC and so they assume that HttpRequest derives from HttpRequestBase, which it does in MVC but not in ASP.NET Forms.I tried using Moq but you can't mock a sealed class, and HttpRequest is unfortunately sealed with no interface.

View 1 Replies


Similar Messages:

Mvc Rhino Mocks Mocking Httprequest Values?

Jul 7, 2010

here Im trying to write a test can I mock a HttpRequestBase to return post values like this? please help as its quite urgent, how can I acheive this?

var collection = new NameValueCollection();
collection.Add("Id", "1");
collection.Add("UserName", "");

[code]...

View 1 Replies

MVC :: Unit Testing + Mocking Session Variable?

May 17, 2010

I have a class which I store in session. Lets say Class A, having an attribute theList. I have a member function that adds an item to theList and returns the count of my list.So I mock my class and set theList to "1,2,3" for my unit test, and test my add function by adding "4".

It returns count "3" instead of "4".

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

.NET HttpRequest From 1.1 To 3.5?

Jan 12, 2010

We have to ASP.NET applications, one in 1.1 and one in 3.5. In order to log our errors in the same location we are going to create a WebService that the 1.1 app can call. If I include an HttpRequest as one of the parameters to the webservice, will there be a versioning problem?

View 1 Replies

How To Get Host Name Without Using HttpRequest

Jan 29, 2010

I'm want to run a "background job" in my ASP.NET application (periodically, as separate thread). And I need host name (DNS name or IP) to do my tasks. The problem - HttpContext.Current may be not available here (it's NULL).

Is there any way to get a host name in not using HttpContext.Current.Request.Url.Host.

View 3 Replies

C# - How To Queries Are Sent Back In An HttpRequest

Aug 11, 2010

I'm going to try to use the WebClient object in .NET to grab the response querystring values sent back by the resource.

I'm familiar with grabbing xml, json, etc. but typically I haven't worked with many NVP type of APIs in terms of grabbing the query immediately from an response sent back from a resource server-side. So how is a query sent back, in the body of a response, header, what? How do you grab it, with the stream object just like you do anything else? This questions relates to the environment I work in C# but really it relates to the web as a whole as well which is why I tagged this in multiple categories as a Request/Response is not MS specific however I am also at the same time trying to utilize the .NET WebClient object.

View 1 Replies

Jquery - Get HttpRequest With A Web Method?

Oct 1, 2010

I have a page web method, and I need to get access to the headers, and particularly the uploaded files. Is this possible? Can a web method receive a file?If not, what would you recommend to upload files without post back? I am using the jQuery forms library that has support for this (and I have had it working with Django), however, I am having a hard time finding answers on how to do this with ASP.NET.

View 2 Replies

Populating HttpRequest.Browser Properties?

Jan 7, 2010

I'm creating HttpContext "by hands" (see [URL]. Does somebody know how can I populate HttpRequest.Browser class's properties (the HttpRequest.Browser.Browser one)? Unfortunately, the HttpBrowserCapabilities class has no the appropriate setter and adding the corresponding http header to the request gives no result.

View 1 Replies

C# - HTTPRequest.Files.Count Never Equals Zero?

Dec 10, 2010

I have a form on an HTML page that a user needs to use to upload a file which posts to an ASPX page. In the code behind, I want to test if a file has actually been loaded.

if (Request.Files.Count > 0)
{
DoStuff(Request.Files[0]);
}
else
{
throw new Exception("A CSV file must be selected for upload.");
}

I am never getting to the else. Is this just how ASP.NET operates? If I have a input element of type file, is it always going to upload a "file" even if one is not selected? What's the proper way to do this? Maybe this?

if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
{
DoStuff(Request.Files[0]);
}
else
{
throw new Exception("A CSV file must be selected for upload.");
}

View 3 Replies

Vb - HttpRequest Maximum Length Exceeded In ASP

May 18, 2010

I'm trying to fix an issue with an application I'm supporting (I didn't write the code). The code takes an SSRS report and renders it in pdf format. Users are sporadically getting the error indicated in the title. There is no rhyme or reason to when the error is generated (a particular report will run one time and throw the error the next). The code is below.

Public Sub OpenReport()
Dim MyParms As New Generic.List(Of ReportParameter)
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim deviceInfo As String = Nothing
Dim streamids() As String = Nothing
Dim warnings As Microsoft.Reporting.WebForms.Warning() = Nothing
Dim bytes() As Byte
Dim format As String = "PDF" ''#to open the report in pdf; report viewer invisible
Try
If dropReports.SelectedItem.Value = "1" Then
If Session("IsBDAP") = True Then
MyParms.Add(New ReportParameter("SCAId", dropSCA.SelectedItem.Value, False))
Else
MyParms.Add(New ReportParameter("SCAId", Server.UrlEncode(Session("SCAId")), False))
End If
MyParms.Add(New ReportParameter("ProviderId", dropProvider.SelectedItem.Value, False))
If dropVisit.Visible = True Then
MyParms.Add(New ReportParameter("VisitId", dropVisit.SelectedItem.Value, False))
End If
MyParms.Add(New ReportParameter("FY", dropContractFY.SelectedItem.Value, False))
ReportViewer1.ProcessingMode = ProcessingMode.Remote
ReportViewer1.ServerReport.ReportServerUrl = New Uri(System.Configuration.ConfigurationManager.AppSettings("ReportServerURI"))
ReportViewer1.ServerReport.ReportPath = Session("ReportsFolder") & "MReport"
ReportViewer1.ServerReport.ReportServerCredentials = New MyReportServerCredentials()
ReportViewer1.ServerReport.SetParameters(MyParms)
''#Code to convert the report to pdf
deviceInfo = "<DeviceInfo>" + "<SimplePageHeaders>True</SimplePageHeaders>" + "</DeviceInfo>"
bytes = ReportViewer1.ServerReport.Render(format, deviceInfo, mimeType, encoding, extension, streamids, warnings)
Dim size As Integer = bytes.Length
ReportViewer1.ServerReport.Refresh()
Response.Buffer = True
Response.Clear()
Response.ContentType = mimeType
Response.AddHeader("content-disposition", "attachment; filename=MReport." + extension)
Response.BinaryWrite(bytes)
ElseIf dropReports.SelectedItem.Value = "2" Then
If Session("IsBDAP") = True Then
MyParms.Add(New ReportParameter("SCAId", dropSCA.SelectedItem.Value, False))
Else
MyParms.Add(New ReportParameter("SCAId", Server.UrlEncode(Session("SCAId")), False))
End If
MyParms.Add(New ReportParameter("ProviderId", dropProvider.SelectedItem.Value, False))
If dropVisit.Visible = True Then
MyParms.Add(New ReportParameter("FollowUpVisitId", dropVisit.SelectedItem.Value, False))
End If
MyParms.Add(New ReportParameter("FY", dropContractFY.SelectedItem.Value, False))
ReportViewer1.ProcessingMode = ProcessingMode.Remote
ReportViewer1.ServerReport.ReportServerUrl = New Uri(System.Configuration.ConfigurationManager.AppSettings("ReportServerURI"))
ReportViewer1.ServerReport.ReportPath = Session("ReportsFolder") & "FReport"
ReportViewer1.ServerReport.ReportServerCredentials = New MyReportServerCredentials()
ReportViewer1.ServerReport.SetParameters(MyParms)
''#Code to convert the report to pdf
deviceInfo = "<DeviceInfo>" + "<SimplePageHeaders>True</SimplePageHeaders>" + "</DeviceInfo>"
bytes = ReportViewer1.ServerReport.Render(format, deviceInfo, mimeType, encoding, extension, streamids, warnings)
ReportViewer1.ServerReport.Refresh()
Response.Buffer = True
Response.Clear()
Response.ContentType = mimeType
Response.AddHeader("content-disposition", "attachment; filename=FReport." + extension)
Response.BinaryWrite(bytes)

I read that the default length limit is 4MB. None of the reports by themselves are even over 350K. I'm wondering if this could be caused by a caching issue. I'm not an expert, so I need some guidance as to how best to solve the problem. I also want to understand why the issue is happening. note that only 2 reports are shown in the snippet - there are about 30+ reports in the full sub. edit - I tried the proposed solution, but it didn't help (I also tried the Fiddler route, but did not see anything glaring). I thought it might be best to clarify. The reports will run fine for a while, but the execution time gradually gets slower and slower until the application eventually displays the error.

View 3 Replies

Difference Between HttpMethod And RequestType Of HttpRequest?

Jan 28, 2010

The HttpRequest class defines two properties:

HttpMethod:

Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.
public string HttpMethod { get; }
The HTTP data transfer method used by the client.

and RequestType:

Gets or sets the HTTP data transfer method (GET or POST) used by the client. public string RequestType { get; set; } A string representing the HTTP invocation type sent by the client.What is the difference between these two properties? When would i want to use one over the other? Which is the proper one to inspect to see what data transfer method was used by the client?The documentation indicates that HttpMethod will return whatever verb was used: such as GET, POST, or HEAD while the documentation on RequestType seems to indicate only one of two possible values: i test with a random sampling of verbs, and both properties seem to support all verbs, and both return the same values:

Testing:

Client Used HttpMethod RequestType
GET GET GET
POST POST POST
HEAD HEAD HEAD
CONNECT CONNECT CONNECT
MKCOL MKCOL MKCOL
PUT PUT PUT
FOOTEST FOOTEST FOOTEST

What is the difference between:

HttpRequest.HttpMethod
HttpRequest.RequestType

and when should i use one over the other? Keywords: iis asp.net http httprequest httphandler

View 2 Replies

Get The Raw Response Header And Body From The HttpRequest?

Feb 18, 2010

Is there a way to get the raw response header and body from the HttpRequest.Response object for debugging when issues arrise?

View 4 Replies

MVC :: Get The Object Of HTTPRequest - Logon User Details

Aug 17, 2010

Anyway I can get the object of HTTPRequest? From View or Action? What I want is to read the logon user name and its email address from active directory.

View 1 Replies

WCF / ASMX :: How To Capture SOAP Fault With HttpRequest

Jun 3, 2010

I use HttpRequest, when there is a SOAP fault, I get 500 error. I read that you can get the SOAP fault info in the response stream, but when there is a 500 error, how do you get the response stream?

View 1 Replies

Web Forms :: How To Extract A Portion Of A String That Is Returned From A HTTPRequest

Jan 19, 2010

im writing a whois lookup page for a clients website and the whois query for .com .biz etc is handled by internic,

i create a HTTPRequest and get the response and it returns a whole webpage with the doctype, head tags and body tags, all i want is the data between the tags <pre> and </pre> how would i get just this from the string that is returned?

View 3 Replies

Change Or Remove HttpRequest Input Arguments In HttpModule

Jan 17, 2011

Is it possible to change or remove http request form inputs in an httpmodule? My goal is to create a security IHttpmodule that will check the request for reasonable values, such as limits on acceptable input and query parameter length, or use the AntiXSS Sanitizer to remove threats, log potential hack attempts, etc. before a request is passed on to a processor.

Because this is a cross cutting concern I'd prefer to find a solution that applies to all requests and affects all ways request values could be accessed, Reqest.Form, Action(model), Action(FormCollection), HttpContext.Current.Request.Form, etc. I'm using MVC and have considered creating custom model binders to clean the data before creating the model instance. But that would be application specific, require remembering to register every model binder and only apply to Action(model).

View 1 Replies

Architecture :: Unit Testing - Testing Private Methods Using PrivateObject?

Feb 23, 2011

Recently for a class to implement unit test for one of its private methods I used PrivateObject by creating private accessor instead of refelection, to which i received a code review comment as below

"My main concern with Private Object is the use of object[] in constructor. It replaces strong typing enforced by compiler with JavaScript-style run-time error detection.Consequently , personally, I would not recommend it."

Comments above confused me beacuse as per my understanding reflection also needs the object[] to invoke any method.

View 2 Replies

Mocking HttpSessionState In .net For Nunit Testing

Mar 28, 2011

I've see n a lot of discussions surrounding HttpSessionState and asp.net MVC.I'm trying to write tests for an asp.net application and to mock the HttpSessionState and if so, how?I'm currently using Rhino Mocks and Nunit

View 1 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

First Request Fails With HTTP 400 (Bad Request) After Reading HttpRequest.InputStream

Oct 24, 2010

I develop an asmx web service (i.e. ASP.NET 2.0). There's a piece of code that may read the contents of the HTTP request (via HttpContext.Current.Request.InputStream) while processing it. I realise that InputStream may only be read once for a request, and I make sure I never try to read it more than once.

The problem seems to be that if InputStream happens to be read during the early stages of the application's lifecycle (e.g. after pskill w3wp, during Application_Start), the HTTP request fails with a HTTP 400 - Bad Request error, with no explanation given, no exception thrown and no entry in the httperr log. If it is read later (e.g. within the web method itself), requests run fine whether InputStream is read or not. Application_Start runs fine if InputStream isn't read.

Is this some sort of ASP.NET bug? IIS bug? Or am I doing something wrong by daring to read InputStream? And if so, is there another way to get a look at the "raw" contents of the request without disturbing the inner workings of IIS/ASP.NET? In short, adding this code within Application_Start is enough to reproduce this error: using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream))reader.ReadToEnd();

View 1 Replies

Cross Page Posting Via HttpRequest || Page.PreviousPage?

Mar 26, 2011

I've been developing classic ASP pages at the job for the past five years and now we are moving to ASP.NET. I'm trying to understand how to get form field values from one page to another and it seems like there is more than one way to do it. In classic ASPI just called request.form collection and got the information. Which way is recommended in .net? Cross Page, Transfer, or HttpRequest?

View 1 Replies

WCF / ASMX :: How To Execute WebService Asmx Link From Default.aspx Page Link Using HTTPRequest And HTTPResponse

Nov 3, 2010

I have spent a couple of days on this one. I have an ASP.NET website that has Linkbuttons on

the Default.aspx page.. I added a WebService to the Website because later on the WebService will

subscribe to a Provider(Feed) of News, Sports and Weather and things like that. So when a Linkbutton

on the Default.aspx page is clicked it will connect to the link in the WebService which will load the News,

Sports or Weather onto the Default.aspx web page.

The problem is I can't get the LinkButton to execute the Link in the WebService. The link will call the page up

to where you see all of the Web References. But then if you want to execute one of those references you

have to click its link and the Invoke button that will follow. My questioh is how can the link on my Default.aspx

page execute the link in the WebService. Now I changed the LinkButton into an <a href> but I still can't execute

the link in the WebServices. I always use www.Microsoft.com as the link when testing and I wasn't sure about the return type

so I put "void" for an HTTPRequest, so below is the link from the Default.aspx web page and below that is he asmx file:

[code]....

View 2 Replies

What Is The Point Of Unit Testing

Apr 3, 2011

I have been looking at the unit testing topic and honestly I have never yet seen it in a live application.

Im a little foggy on the subject....
A simple example is if I am populating a listbox with data, I would know through debugging if the data is being populated and if it wasnt it would probably be easy to figure out why. Futhermore I couldnt possibly put it in production if it wasnt work so, why would I need to do a unit test? I dont see the point of it.

View 4 Replies

MVC :: Unit Testing View?

Mar 18, 2011

In MVC, the unit testing is primarily surrounding the controllers. The Model is rarely tested, and the View not at all. What is the consensus on this?

View 13 Replies







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