Henkolicious
Henkolicious

Reputation: 1411

xunit pass class method as inline data

Is it possible to pass an object method as inline data to a xunit test?

I have a few object methods to set some object state that I would like to pass to a [Theory] as [InlineData] like so:

private readonly SomeObject _sut;

public SomeConstructorForTests()
{
    _sut = new("foo", "bar");
}

[Theory]
[InlineData(_sut.MethodToSetState)]
[InlineData(_sut.SomeOtherMethodToSetState)]
public void some_test(Action set_pre_state)
{
// arrange
set_pre_state();

// act
...

// assert
...
}

Getting a syntax error at the inline data "_sut" --> An object reference is required for the non-static field, method, or property.

I simply do not want to create a lost of tests when it should be possible to inline it, keep it DRY :)

Upvotes: 1

Views: 2041

Answers (1)

Jakob
Jakob

Reputation: 1216

You need to use ClassData for this. Annotate your method with

[Theory]
[ClassData(typeof(TestDataObject))]

and TestDataObject needs to extend TheoryData<SomObject>.

You can then call Add(new SomeObject("foo", "bar")) in the constructor of the TestData class.

Upvotes: 2

Related Questions