StackOverflow in .NET unit testing when references are circular

做~自己de王妃 提交于 2020-01-24 13:17:18

问题


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?


回答1:


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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/48392039/stackoverflow-in-net-unit-testing-when-references-are-circular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!