0

I have an application and i have written MSUnit cases for services layer. My question is how to write MSUnit cases for methods which are in code behind files in asp.net.

Or is it necessary to write test cases for UI layer?

k.m
  • 30,794
  • 10
  • 62
  • 86
Shankar
  • 3
  • 4
  • 2
    If you want to test the UI layer, there's a great tool for FireFox called Selenium that allows you to record tests. Of course, if you change your UI, you'll need to change the tests, but that'll happen with any tool... – Tim Nov 12 '14 at 13:09

4 Answers4

1

That would be hard - these are not designed in a way to be easily testable. ASP.NET MVC improves on that.

However, you should keep the code-behind really thin, so you can cover the key functionality with testing other classes.

Bojan Bjelic
  • 3,522
  • 1
  • 17
  • 18
1

You can use WatiN (http://watin.org/), which was built just for that. From their page:

[Test] 
public void SearchForWatiNOnGoogle()
{
  using (var browser = new IE("http://www.google.com"))
  {
    browser.TextField(Find.ByName("q")).TypeText("WatiN");
    browser.Button(Find.ByName("btnG")).Click();

    Assert.IsTrue(browser.ContainsText("WatiN"));
  }
}
Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
0

As Bojan Bjelic wrote, the classes from ASP.NET code-behinds are hard to instantiate outside of the ASP.NET environment and therefore the are hard to test. Therefore, I'd suggest that you examine the Model-View-Presenter pattern, especially its Passive View variant.

The idea is to move all logic from a code-behind file into a Presenter class that is an easily-instantiated and not platform dependent POCO. That presenter will be easily testable then. The code-behind code will be pretty "dummy", as the name "passive view" suggests.

Here is an example for WinForms but the pattern works for ASP.Net and even for Android Java as well.

You can test those presenters really quickly, given the tests are written properly. A typical test takes a fraction of a second.

Community
  • 1
  • 1
Ivan Gerken
  • 914
  • 1
  • 9
  • 21
0

I found a good example here (check out Codor's answer at the bottom of the page)

and was able to use it in my code to call a private function in the code behind for testing.

 //page 
//include a using at the top Project.Folder where page is located
PageName pageObject = new PageName();

//public function
ReturnType returnPublicObject = pageObject.METHOD_NAME(comma, separated, args);

//private function
ReturnType returnPrivateObject= (ReturnType)pageObject.GetType()
           .GetMethod("METHOD_Name", 
           BindingFlags.NonPublic | BindingFlags.Instance)
           .Invoke(pageObject, new object[] { comma, separated, args });
Ham Jam
  • 1
  • 3