Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give object as parameter for test

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)
{
    // ...
}
like image 370
Snæbjørn Avatar asked May 12 '15 22:05

Snæbjørn


1 Answers

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]

like image 184
robi-y Avatar answered Oct 18 '22 06:10

robi-y