【问题标题】:How to break dependency on StreamReader's readLine() method in microsoft fakes unit testing?如何在 Microsoft fakes 单元测试中打破对 StreamReader 的 readLine() 方法的依赖?
【发布时间】:2016-02-27 15:51:49
【问题描述】:

这是我要测试的方法之一中的代码:

    using (var sr = new StreamReader(myFile))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                if (line.Equals("completed"))
                {
                    continue; //here it is getting called infinite times
                }

                if(line.Equals("processed"))
                {
                    break;
                }
            }
        }

在我的测试方法中,我在 shim 的帮助下编写了以下代码:

            ShimStreamReader.ConstructorString = delegate (StreamReader @this, string @string)
            {
                var reader = new ShimStreamReader(@this);
                reader.ReadLine = () =>
                {
                    return "completed";
                };
            };

现在我不想传递文件。相反,我想传递字符流或字符串。 上面的测试代码按预期调用并打破了 new StreamReader(myFile) 的依赖关系并进入了 while 循环。 一旦在 while 循环中输入它, sr.ReadLine() 就会一直返回“已完成”。所以我被困在这里。我将如何在这里停下来,或者我将如何编写输入字符串,以便我的第一次调用返回在第二次调用 sr.ReadLine() 时完成,它应该返回 null,然后中断循环?

【问题讨论】:

    标签: unit-testing readline microsoft-fakes


    【解决方案1】:

    您在这里更喜欢一般的编码问题,而不是假货。您需要做的就是添加一个标志并在您准备好结束输入时设置它。这是我使用的代码

        private bool _lineSent = false;
    
        [TestMethod]
        public void ReaderTest()
        {
            using (ShimsContext.Create())
            {
                ShimStreamReader.ConstructorString = (reader, s) =>
                {
                    ShimStreamReader shimReader = new ShimStreamReader(reader);
                    shimReader.ReadLine = () =>
                    {
                        if (!_lineSent)
                        {
                            _lineSent = true;
                            return "completed";
                        }
                        else
                        {
                            return null;
                        }
                    };
                };
    
                ClassToTest testInstance = new ClassToTest();
                testInstance.ReadStream();
            }
        }
    

    顺便说一句,根据您的水平和您想要学习的内容,您可能希望研究依赖注入并使用存根而不是填充程序。 Shim 很方便也很不错,但是对于您控制下的新开发和代码,请尝试使用存根。

    【讨论】:

    • 感谢您的努力 Doobop。虽然这是一个迟到的回复,但非常感谢 DooBop。它也可能对某人有所帮助。我实现的是,创建代码以使用我的预期输入创建一个文件并将其传递给阅读器,然后我能够测试我的方法。传递文件输入 dint 进入无限循环。 :) 干杯谢谢 :)
    猜你喜欢
    • 2013-02-27
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    相关资源
    最近更新 更多