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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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:
Method 2
If you want testable ASP.NET WebForms code, check out this project.
http://webformsmvp.com/
Method 3
Web forms really wasn’t built to be run through unit testing. Here’s a good article on what I’m talking about. If you really want your pages to be testable I’d consider moving over to asp.net mvc or mvp.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0