views:

110

answers:

3

I have an abstract class that a User control inherits from, that I would like to write unit tests for. I understand I need to create a mock class to be able to test abstract classes. The abstract class has references to UI controls (ex: a base method that has web control as an argument). My question is, how would I write unit tests to any methods that references controls in the System.Web.UI namespace?

Thanks

EDIT: Here's an example of the code I have

public abstract SpecialUserControl : System.Web.UI.UserControl
{
    protected virtual void DoSomething(TextBox txtBoxName)
    {
         //Here's the logic I want to write unit test for
    }
}

In ascx.cs

public partial class MyUsercontrol : SpecialUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
    base.DoSomething( txtBoxName );
    }

}

In aspx.cs

public partial class SomePage : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
       //Dynamically loaded
       LoadControl("MyUserControl.ascx");
    }

}
A: 

From what I understand of your problem, you're going to need to create a control for your abstract-derived class to initialize from. So you will need to create a concrete class to test your abstract class; you will also need to mock up the web control (from your example) that it will use to initialize itself.

McWafflestix
+1  A: 

and my response would be 'What is preventing you from writing those tests?' (I'd need more code-context to give a more detailed answer)

Treat them just like any other collaborator/dependency for your code. If the UI Controls are easy to create in a test suite - you should just go ahead & setup their state, act on them and assert your expectations.
If the UI Controls are not easy or expensive to create, abstract them away with an interface (containing just the methods you us to interact with the control) & plug in mock/fake/stub implementations.

Also might I add, keep the UI as thin as possible.

Gishu
+1  A: 

You could try and create instances of those web controls for the purposes of your test, or you could mock them up as well if that isn't possible. If you foresee needing mockups for multiple sets of unit tests, don't hesitate to spend the time.

It would be easier if your code depended only interfaces rather than concrete classes, because then you could just mock up an interface without having to mock up the entire class.

It would be still easier if there were some abstraction layer between your code and the System.Web.UI controls. This might both make it easier to test as well as to maintain.

I guess my point is that there's such a thing as designing code to be unit-testable.

It's possible there would be some more concrete advice to give if you gave a more concrete scenario.

Drew Hoskins