How to write unit tests for web applications and controls
I am just learning unit testing. I am using NUnit to create tests for a VB.NET project.
The project I'm working on is part of a framework that will be used by people who build ASP.NET websites. It includes a base class (which inherits System.Web.HttpApplication
) that users of my framework inherit from their application class.
The project also contains a number of composite controls.
At the moment, I cannot figure out how you are going to write tests for the base class of the application or any of the composite controls.
In the case of an application base class, should the Unit Test project include a class that inherits from it and then test it?
Any pointers would be appreciated!
Thank.
source to share
I would test the base class of the application indirectly by subclassing and testing this as you said.
For controls, I would use Selenium: http://selenium.seleniumhq.org/ .
source to share
It is no longer supported, but there is NUnitAsp .
[Test]
public void TestExample()
{
// First, instantiate "Tester" objects:
LabelTester label = new LabelTester("textLabel");
LinkButtonTester link = new LinkButtonTester("linkButton");
// Second, visit the page being tested:
Browser.GetPage("http://localhost/example/example.aspx");
// Third, use tester objects to test the page:
Assert.AreEqual("Not clicked.", label.Text);
link.Click();
Assert.AreEqual("Clicked once.", label.Text);
link.Click();
Assert.AreEqual("Clicked twice.", label.Text);
}
source to share
I was able to do this by creating a stub for the web control that I am testing with a module and calling the protected RenderContents () method and inspecting the HTML:
[Test]
public void ConditionQueryBuilderTest_RendersProperHtml()
{
var sw = new StringWriter();
var queryBuilder = new ConditionQueryBuilderStub
{
ID = "UnitTestbuilder",
QueryBuilderURL = @"\SomeAspxPage\SomeWebMethod",
ResetQueryBuilderURL = @"\SomeAspxPage\OnQueryBuilderReset",
FilterValuesCollection = new Dictionary<int, string> { {15, "Some Condition"}}
};
queryBuilder.RenderAllContents(new HtmlTextWriter(sw)); // This is a method in my stub that exposes RenderContents()
AppendLog(sw.ToString());
Assert.AreEqual(ExpectedHtml, sw.ToString());
}
source to share