当引用为循环时,.NET 单元测试中的 StackOverflow [英] StackOverflow in .NET unit testing when references are circular

查看:13
本文介绍了当引用为循环时,.NET 单元测试中的 StackOverflow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我注意到时,我正在测试其他循环参考电阻:

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

导致 XUnit 运行程序停止和控制台日志:

resulted in XUnit runner halt and console log:

活动测试运行已中止.原因:进程因 StackOverflowException 而终止.

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

我在 MStest 上进行了测试,结果相同.有没有解决的办法?这是一个错误,还是打算以这种方式停止执行?

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?

推荐答案

您不是在进行循环引用.您正在制作一堆指向另一个的引用(如果您说是链表),最终会导致堆栈溢出异常,因为堆栈已满.

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

这篇关于当引用为循环时,.NET 单元测试中的 StackOverflow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆