Category Archives: C#

Testing ASP.NET with Sessions and HttpContext

In my last post I advocated strongly for writing tests for any project that you inherit that does not have them.

As I begin to build a test suite for the code I am now responsible for, I am going to be writing about challenges I run into writing tests in a framework with which I am not heavily experienced.

Mocks Are Your Friend

When writing tests, it is important to isolate the code that you are testing to make sure that only it is being tested. You usually want to test specific behavior from a specific scenario.

One of the ways you can do this is by mocking or faking the responses from any other parts of the code that it calls.

The framework that I have decided to use for this is called Moq and makes it pretty easy to create a small stand in object that fakes the response you want.

Using these I was able to isolate problem areas in the test to determine the resources I needed to get the code to operate correctly.

HttpContext in Your Test

The project I am working on is an ASP.NET application. The way it was designed relies on redirects, the HttpContext.Current, and Sessions. This means that testing things can get tricky.

I was trying to Mock out the responses I needed for my test and made good headway doing so. But after doing a bunch of research along with trial and error, the best place I found to create the HttpContext for the test is in the TestInitialize portion of the test.


        [TestInitialize]
        public void TestInit()
           {
            var request = new HttpRequest("", "http://localhost", "");
            var response = new HttpResponse(new StringWriter());
            var testHttpContext = new HttpContext(request, response);
            HttpContext.Current = testHttpContext;
           }

Their are many cases where you would just want to make a simple Mock of the HttpContext and whatever you were trying to get out of it in the function, but the function I was testing used so many aspects of it that it just made sense to create one in the test initialization.

Session in Your Test

The main problem I ran into was with Session. Every use of Session in the code I was testing gave an error of “Object reference set to Null.” Additionally their did not seem to be a good way to Mock it out. It is not created by default in a new HttpContext, so putting that in the TestInitialize section did not work.

After doing a lot of digging, I finally found a way to add a new Session to the HttpContext. You have to create a HttpSessionStateContainer and then use the SessionStateUtility to add it to your HttpContext object in the TestInitialize code.


var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                            new HttpStaticObjectsCollection(), 10, true,
                                            HttpCookieMode.AutoDetect,
                                            SessionStateMode.InProc, false);
SessionStateUtility.AddHttpSessionStateToContext(testHttpContext, sessionContainer);

If you are tearing your hair out trying to figure out how searching for things like “C# asp.net test set httpcontext” or “C# asp.net test mock session”, then hopefully this helps you.

Happy Testing

Xamarin Forms Entry

I am rewriting the Cashflow calculator app that I made last fall from Java to a Xamarin Forms app. If I ever decide to release to iOS this will make it much easier.

One of the workhorses for this app is the Entry form element. This is your standard input field from the keyboard.

There are two features that I want to talk about today. Setting the keyboard type and Completed and TextChanged events.

Setting the Keyboard

The Entry element lets you specify the keyboard type like you would expect. There is the Default – the standard keyboard on your device, Numeric – number only entry for things like calculators and money (the one I am using the most), also Telephone, Url, Email, and Chat.

If you have done any sort of UI programming before, you know that limiting the characters that your user can put in significantly reduces the number of potential errors.

XAML Example:


<Entry Keyboard="Numeric" />

The Completed Event

Whenever the user finishes filling out the field and hits the enter or next key, the Completed event gets fired. You can hook up your Entry field to call a function whenever this happens.

For me whenever the user changes one of the values in my form, I recalculate the cashflow value of the property they are putting in. This way they get instant feedback on what one value has to the overall calculation.

XAML Example:


<Entry Completed="CalculateCashflow" />

Where CalculateCashflow is a function in the XAML’s code behind file.

TextChanged Event

This allows you to call a function as soon as the text in a field gets changed, not just when you are done changing it. It might seem like an odd thing to have since we already have a Completed event, but I will give you an instance I plan on using it for.

A couple of my form fields will be connected and be different representations of the same value. For instance, when estimating cashflow of a property it is common to estimate the repair and vacancy costs as percents of the rent.

In this case I will have a pair of split fields that are related. A repair_cash Entry and a repair_percent Entry. Whenever one of them changes, I want the other one to be updated.

XAML Example:


<Entry x:Name="repair_cash" TextChanged="SetRepairPercent" />
<Entry x:Name="repair_percent" TextChanged="SetRepairCash" />

Where SetRepairPercent and SetRepairCash are functions in the XAML’s code behind file.

Note that the Completed event callback function takes a sender object and an EventArgs object while the TextChanged event callback function takes a sender object and a TextChangedEventArgs object.

Really enjoying Xamarin so far. Looking forward to releasing a couple apps with it this year.