mercredi 2 septembre 2015

How to dynamically subclass (or implement) a base class (or an interface)?

I want to test a parametric Abstract Factory Method implementation:

public class AbstractChairFactory
{
  public static ChairFactory GetFactory(IChairType type)
  {
    if(type is ChairA)
       ...
    if(type is ChairB)
      ...
    throw new Exception("Unknow type");
  }
}

interface IChairType {}
class ChairA : IChairType
{
}

class ChairB : IChairType
{
}

AbstractChairFactory.GetFactory method should throw exception when instance of any type rather than of type IChairType is passed to it.

One way is to design yet another class FakeType:

class FakeType : IChairType {}

and pass it throgh.

But is there any better way to do so? I mean a way to dynamically implement IChairType. Something like this:

   IChairType fakeInstance = SomeMagic.GetAFakeVersionOf<IChairType>();

   try
   {
        AbstractChairFactory.GetFactory(fakeInstance);
        Assert.Fail();
   }
   catch
   {

   }

Aucun commentaire:

Enregistrer un commentaire