Okiba
Okiba

Reputation: 229

xUnit - Using Context from SetFixture() In the Test Class Constructor

EDIT: Question revised.

I'm migrating few tests from nUnit to xUnit, and I have a question regrading the relationship between the SetFixture() method and the constructor. My tests have common setup methods. According to the xUnit manual, [Setup] code should now go into the constructor. Consider this example:

public class MyTestClass : IUseFixture<TestFixture> {

    private TestObject m_MyObject;

    public MyTestClass() {
        m_MyObject.Login()
    }

    public void SetFixture(TestFixture data) {
        m_MyObject = data.TestObject;
    }

    [Fact]
    public void MyTest() {
        Console.Writeline("My Test");
    }

TestObject is being initialized once on my Fixture Class. In SetFixture(), I'm assigning it to a local member so the test-code may use it. However, I'm also using this object during Setup. As the Constructor running before the SetFixture(), I'm unable to use my TestObject. What would be the solution for that issue?

Upvotes: 2

Views: 2724

Answers (1)

Ruben Bartelink
Ruben Bartelink

Reputation: 61865

EDIT: Heavily edited from rambling initial response - The first two comments (from the OP and me) are rendered obsolete by the edit.


You're running into a weakness in design of the xUnit v1 IUseFixture mechanism which applies generally to the use of Setter Method Injection [pattern documented in the excellent Dependency Injection in .NET book] . (See related discussion in context of same patterns in Ninject)

The ctor and SetFixture are indeed called once per test. In general, you should not be doing anything in the SetFixture other than stashing the value. The ctor of the Fixture is the place to do any Fixture-related setup (obviously that'll only happen once).

What I tend to do instead is to make my Test Classes static and then lean on AutoFixture.xUnit to avoid the SetFixture and/or stateful Test Classes but that may or may not be appropriate in your case.

In xUnit v2, you can add Fixtures as parameters to the Test Class constructor which would obviate the problems you're encountering. This mechanism also works especially well in conjunction with C# 6 new primary constructor mechanism (and obviously F# as everything does :)

Upvotes: 1

Related Questions