Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 453
Piotr Falkowski Avatar asked Jan 22 '18 23:01

Piotr Falkowski


2 Answers

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;
}
like image 63
M.kazem Akhgary Avatar answered Sep 27 '22 16:09

M.kazem Akhgary


I also encountered this problem: Visual Studio just quietly stopped the test run with inconclusive result and it did not pinpoint what caused the problem. It just stopped the tests with blue icon indicating inconclusive result. In the Output window I noticed the same error message:

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

The solution was to run the test as "Debug Selected Test". Visual Studio then highlighted one of the lines participated in circular reference loop. One should place a break-point on that line and Debug the test once again. From this point debugger will step though the circular reference path.

like image 24
VeganHunter Avatar answered Sep 27 '22 16:09

VeganHunter