5

I trying to write a test that checks that a method isn't overwritten incorrectly in derived classes. So I tried the following. But no matter what I try it doesn't seem to allow me to "inject" my object.

[Theory]
[xxxData(new BaseClass())]
[xxxData(new DerivedClass())]
public void Test_Stuff(BaseClass obj)
{
    // ...
}
Snæbjørn
  • 10,322
  • 14
  • 65
  • 124
  • A complete guide that sends complex objects as a parameter to Test methods [complex types in Unit test](https://stackoverflow.com/a/56413307/7487135) – Iman Bahrampour Jun 02 '19 at 08:48

1 Answers1

14

Assuming I understand your goal, I see two ways:

  1. Using InlineDataAttribute and passing Types
  2. Using MemberDataAttribute (PropertyData in xunit.net v1)

    [Theory]
    [InlineData(typeof(BaseClass))]
    [InlineData(typeof(DerivedClass))]
    public void Test_Stuff(Type type/*BaseClass obj*/)
    {
        var obj = Activator.CreateInstance(type) as BaseClass;
        CheckConstrain(obj);
    }
    
    
    [Theory]
    [MemberData("GetObjects")]
    public void Test_Stuff2(BaseClass obj)
    {
        CheckConstrain(obj);
    }
    
    public static IEnumerable<object[]> GetObjects
    {
        get
        {
           return new[] 
           {
            new object[] { new BaseClass() },
            new object[] { new DerivedClass() }
           };
        }
    }
    
    private static void CheckConstrain(BaseClass baseClass)
    {
        Assert.True(baseClass.Foo() <= 1);
    }
    

See also this related answer Pass complex parameters to [Theory]

Community
  • 1
  • 1
robi-y
  • 1,687
  • 16
  • 25