Search code examples
c#unit-testingstack-overflow

StackOverflow in .NET unit testing when references are circular


I was testing something else for circular reference resistance when I noticed:

    public class Foo
    {
        private Bar myBar = new Bar();
    }

    public class Bar
    {
        private Foo myFoo = new Foo();
    }

    [Fact]
    public void CircularReferenceTest()
    {
        var foo = new Foo();
        var bar = new Bar();
    }

resulted in XUnit runner halt and console log:

The active test run was aborted. Reason: Process is terminated due to StackOverflowException.

I tested it on MStest and had same result. Is there a way around this? Is it a bug, or it's intended to stop execution in that way?


Solution

  • you are not making circular reference. you are making bunch of references pointing one to another (linked list if you say), eventually it causes Stack overflow exception because stack becomes full.

    Here is how to make circular reference. I don't think you can leave fields private, because two classes must somehow know each other at some point. (i.e at some point this connection must be made)

    public class Foo
    {
        public Bar MyBar { get; set; }  
    }
    
    public class Bar
    {
        public Foo MyFoo { get; set; } 
    }
    
    public void CircularReferenceTest()
    {
        var foo = new Foo();
        var bar = new Bar();
    
        foo.MyBar = bar;
        bar.MyFoo = foo;
    }