Peet Whittaker
Peet Whittaker

Reputation: 770

How to unit test constructor when using nested test classes

Assuming I have some logic in a class constructor that I wish to unit test, how would I structure it if I am using xUnit.net and nested test classes for each method?

using Xunit;

public class MyClass
{
    public MyClass()
    {
        // Some logic to test
    }

    public int GetResult()
    {
        return 123;
    }
}

public class MyClassFacts
{
    // How to test MyClass constructor?

    // Nested classes to test each of MyClass' methods
    public class GetResult
    {
        [Fact]
        public void IsCorrect()
        {
            var myClass = new MyClass();
            int result = myClass.GetResult();
            Assert.Equal(123, result);
        }

        // Other tests for MyClass.GetResult()...
    }
}

Upvotes: 1

Views: 2153

Answers (1)

timothyclifford
timothyclifford

Reputation: 6969

You're already testing it in your IsCorrect() test technically but if you want an explicit test:

using Xunit;

public class MyClass
{
    public MyClass()
    {
        // Some logic to test
    }

    public int GetResult()
    {
        return 123;
    }
}

public class MyClassFacts
{
    [Fact]
    public void Ctor()
    {
        var myClass = new MyClass();
        Assert.NotNull(myClass);
        // Any other asserts you require
    }

    // Nested classes to test each of MyClass' methods
    public class GetResult
    {
        [Fact]
        public void IsCorrect()
        {
            var myClass = new MyClass();
            int result = myClass.GetResult();
            Assert.Equal(123, result);
        }

        // Other tests for MyClass.GetResult()...
    }
}

Upvotes: 1

Related Questions