Unit-test template template method template

Assume the following implementation of the template method:

public abstract class Abs
  {
    void DoYourThing()
    {
      log.Info("Starting");
      try
      {
        DoYourThingInternal();
        log.Info("All done");
      }
      catch (MyException ex)
      {
        log.Error("Something went wrong here!");
        throw;
      }
    }

    protected abstract void DoYourThingInternal();

  }

Now there is a lot of information on how to test the class Abs, and make sure it is called DoYourThingInternal.
However, suppose I want to check the class Conc:

 public class Conc : Abs
  {
    protected override void DoYourThingInternal()
    {
      // Lots of awesome stuff here!
    }
  }

I would not want to do conc.DoYourThing(), as this will call the parent method, which has already been tested separately.

I would like to test only the override method.

Any ideas?

+5
source share
5 answers

DoYourThingInternal() DoYourThing() ( , ), , 2 . , DoYourThingInternal() , DoYourThing(). , DoYourThing() DoYourThingInternal().

, DoYourThing(), Abs DoYourThingInternal().

() , , DoYourThing(). , Abs, .

, DoYourThing():

public abstract class AbsBaseTest
{
  public abstract Abs GetAbs();

  [Test]
  public void TestSharedBehavior() 
  {
    getAbs().DoYourThing();

    // Test shared behavior here...
  }
}

[TestFixture]
public class AbsImplTest : AbsBaseTest
{
  public override Abs GetAbs()
  {
    return new AbsImpl();
  }

  [Test]
  public void TestParticularBehavior()
  {
    getAbs().DoYourThing();

    // Test specific behavior here
  }
}

. http://hotgazpacho.org/2010/09/testing-pattern-factory-method-on-base-test-class/

, unit test ( , NUnit ).

+2

, "" , . mock, Conc :

public class MockConc: Conc
  {
    void MockYourThingInternal()
    {
      DoYourThingInternal()
    }
  }
+3

"tdd", , , "".

tdd, -

  • - , (, Conc1)
  • Refactor
  • . , (, Conc2)
  • Refactor

"6" , , Conc1 Conc2 . , , .

, , (= ). , , ( ). , , ( ) . ? , , , , . , - , .

, , IMO . , - .

+2
source

How about attaching an interface to Abs and ridicule? Ignoring calls or waiting for them?

0
source

You can do this in several ways, many of which are already registered here. Here's the approach I usually take: inherit the test case from a particular class.

public ConcTest : Conc
{
    [Test]
    public void DoesItsThingRight()
    {
         var Result = DoItsThingInternal();
         // Assert the response
    }
}

Hope this helps!

Brandon

0
source

All Articles