Can we write test methods in .aspx.cs page? If yes then how? I need to write test method for the code which is in Page_Load method. Please suggest if there is any solution.
Add unit test project when creating the applicationCreate a new ASP.NET Web Application named StoreApp. In the New ASP.NET Project windows, select the Empty template and add folders and core references for Web API. Select the Add unit tests option. The unit test project is automatically named StoreApp.
We have an option to create a Unit test project when we create a Web API project. When we create a unit test project with a web API project, Visual Studio IDE automatically adds Web API project reference to the unit test project.
Unit tests work like a "safety net" to prevent us from breaking things when we add features or change our codebase. In addition, unit tests work like a living documentation. The first end-user of our code is our unit tests. If we want to know what a library does, we should check its unit tests.
Probably you can, but it will be much cleaner if you extract the logic of the Page_Load
method into a model class and then test it separately.
Sample:
// Home.aspx.cs
Page_Load()
{
//Lots of code here
}
// or else Home.aspx.cs
Page_Load()
{
Foo f = new Foo();
var result = f.DoThings();
}
//Unit test
Page_Load_FooDoesThings()
{
//Arrange
Foo f = new Foo();
var expected = ...;
//Act
var actual = f.DoThings();
//Assert
Assert.AreEqual(expected, actual)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With