Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can We write Unit test methods in .aspx.cs page?

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.

like image 886
Pravin Sonawane Avatar asked Dec 18 '12 09:12

Pravin Sonawane


People also ask

How can use unit testing in asp net?

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.

Is it possible to unit test Web API?

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.

How do unit tests work C#?

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.


1 Answers

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.

Why?

  • Reuse logic of the method in other pages
  • Better separation of model and presentation
  • Cleaner code that is easier to test

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)
}
like image 194
oleksii Avatar answered Oct 18 '22 14:10

oleksii