Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test ASP.net Page_Load

How can create a unit test for the the Page_Load function in ASP.net?

I am using build in Visual Studio Unit test frame work. I want to create a unit test that check the Elements of the web page and their values.

I know about selenium and its abilities in unit testing.

This is the web Page to test WebPageControl.ascx.vb:

   Public Class WebPageControl
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            TextBox.Visible = False
        End Sub
End Class

This is the Unit test WebPageControlTest.vb:

Public Class WebPageControlTest
    Public Sub PageLoadTest()

        Dim target As WebPageControl_Accessor = New WebPageControl_Accessor() 
        Assert.IsFAlse(target.TextBox.Visible)
    End Sub
End Class

After I do this I still get an error

Test method RechargeTest.WebPageControlTest.PageLoadTest threw exception: System.NullReferenceException: Object reference not set to an instance of an object.
like image 480
Whitecat Avatar asked Apr 11 '11 17:04

Whitecat


People also ask

What is Page_Load method in asp net?

Your web form has a method called Page_Load. This method is called each time your page is loaded. This includes: 1. The first time the page is loaded, e.g., when a user enters the url to it or clicks on a link to it.

Why write unit tests?

They enable you to catch bugs early in the development process. Automated unit tests help a great deal with regression testing. They detect code smells in your codebase. For example, if you're having a hard time writing unit tests for a piece of code, it might be a sign that your function is too complex.


1 Answers

You're probably not going to be able to new up a Page outside of the ASP.NET runtime.

You may want to google around for the MVP (Model-View-Presenter) pattern under ASP.NET. It makes testing web code a lot easier IMHO. This article is a good starting point:

http://haacked.com/archive/2006/08/09/ASP.NETSupervisingControllerModelViewPresenterFromSchematicToUnitTestsToCode.aspx

like image 122
rsbarro Avatar answered Oct 19 '22 23:10

rsbarro