Cleaner page validation testing with generics
The refactored and (hopefully) less confusing version of the page validation test fixture. Now there is no need to implement any abstract methods in your test fixture but just inherit the base class with proper generic type. Much lazier way to do things...
[TestFixture]
public abstract class BaseValidationTestFixture<T> where T : System.Web.UI.Page,
ITestableValidationContainer
{
protected T testPage;
[SetUp]
public virtual void SetUp()
{
testPage = Activator.CreateInstance();
ResurrectControls();
testPage.SetupValidators();
}
private void ResurrectControls()
{
BindingFlags flags =
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
foreach (FieldInfo field in testPage.GetType().GetFields(flags))
{
if (typeof (WebControl).IsAssignableFrom(field.FieldType))
{
ConstructorInfo constructor = field.FieldType.GetConstructor(new Type[0]);
if (constructor != null)
{
WebControl toAdd = (WebControl)constructor.Invoke(new object[0]);
toAdd.ID = field.Name;
field.SetValue(testPage, toAdd);
testPage.Controls.Add(toAdd);
if (toAdd is BaseValidator) testPage.Validators.Add((BaseValidator)toAdd);
}
}
}
}
}
As you can see, the ITestableValidationContainer interface is still in use. The concrete validation test will be something like this:
[TestFixture]UPDATE: We have to add validation controls to the Page Validators collecion manually. Also it makes sense to expose control accessor methods, like void SetControlValue(string id, object value) and WebControl GetControlValue(string id) so we can access controls whcih are protected on the page.
public class ValidationFixture : BaseValidationTestFixture<MyPage>
{
...
}
No comments:
Post a Comment