Search code examples
c#unit-testingasp.net-mvc-2design-patternschain-of-responsibility

Design Patterns: Many Methods Share The Same First Step


Is there a design pattern that can help me avoid repeating DoThisStepFirst() in many methods?

class Program
{
    static void Main(string[] args)
    {
        Method1();
        Method2();
        MethodN();
    }

    private static void DoThisStepFirst()
    {
        // Implementation
    }

    private static void Method1()
    {
        DoThisStepFirst();
        // Implementation
    }

    private static void Method2()
    {
        DoThisStepFirst();
        // Implementation
    }

    // {...}

    private static void MethodN()
    {
        DoThisStepFirst();
        // Implementation
    }
}

EDIT 1: Suffice it to say, this is a contrived example.
My actual implementation includes method signatures with parameters and non-trivial operations in each method.

EDIT 2:

  • @Marc Gravell suggested Aspect Oriented Programming. Yes, that might help me here.
  • I'm also thinking that the Chain-of-Responsibility pattern might help me here as well.

@Charlie Martin wanted to know more about the program. So here's what I'm actually trying to do.

  • I'm trying to set up a test harness to run against an ASP.NET MVC 2 application for 'm' controllers and 'n' controller methods.
  • The MVC application is tightly coupled with SessionState. For various reasons, I can't mock SessionState.
    • So inside of the DoThisStepFirst() method, I'd like to initialize SessionState.
    • And after initializing SessionState, I'd like to proceed to a specified method (which is why I suspect that I might be seeking the 'Chain of Responsibility' design pattern).

Solution

  • If it's a Test Harness, then your Unit Test framework should have a TestFixtureSetup method, it'll run first before your tests are run:

    For NUnit:

    [TestFixtureSetUp]
    public void Setup()
    {
    
    }
    

    For MSTest:

    [TestInitialize()]
    public void Startup()
    {
        //Do setup here
    }