Can we write Unit test methods on the .aspx.cs page?

Can we write test methods on the .aspx.cs page? If so, how? I need to write a test method for code that is in the Page_Load method. Please suggest if there is any solution.

+6
source share
3 answers

You can probably, 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?

  • Reusing the method in other pages
  • The best separation of model and presentation
  • Clean code that is easier to test

Example:

 // 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) } 
+4
source

You can write a test method anywhere, you just need to use the 3A rule (Arrange, Act, Assert) and decorate your methods based on the testing structure used. You can test almost everything using the testing framework, properties, methods, etc.

However, it is best practice to create a separate test project.

Also, Page_Load , like other page lifecycle methods, is not a good option for testing, because it will be cumbersome to test it. I agree with "oleksii" that functionality is something we can test outside of the Page_Load method.

+3
source

Actually, you can. If you add some testing method to Page_Load , this is programmatically normal. But you should not . Because if you can define your testing methods in your Page_Load , your test will work without having to load each page. This is not the next method in unit testing. This is why Visual Studio creates a separate test project.

+1
source

All Articles