【问题标题】:C# SystemWrapper mock File.ReadAllLinesC# SystemWrapper 模拟 File.ReadAllLines
【发布时间】:2016-05-22 01:56:27
【问题描述】:

在一种方法中,我通常会这样做:

string[] lines = File.ReadAllLines(filename);

为了测试,我希望能够模拟出文件系统,并且我听说过关于 SystemWrapper 的正面 cmets,所以我想使用这个库。

据我了解,使用 SystemWrapper 需要我进行基于接口的调用。没关系。所以我上面的代码行变成了:

string[] lines = new FileWrap().ReadAllLines(filename);

现在,我的测试方法如下所示:(我将 Microsoft.VisualStudio.TestTools.UnitTesting 与 Rhino Mock 结合使用)

[TestMethod()]
public void Test_this_method()
{
    IFileWrap fileWrapRepository = MockRepository.GenerateMock<IFileWrap>();
    fileWrapRepository.expect(x => x.ReadAllLines("abc.txt").Return(new string[] {"Line 1", "Line 2", "Line 3"});

    MethodThatReadsLines();
}

这个例子改编自 SystemWrapper 的 Getting Started 页面上的一个例子。

但是,当我这样做时,该方法并没有调用我的模拟方法,而是调用File.ReadAllLines,这不是我所期望的。

模拟File.ReadAllLines的正确方法是什么?

【问题讨论】:

    标签: c# unit-testing mocking filesystems systemwrapper


    【解决方案1】:

    起订量是测试替身,要调用模拟,您必须实际调用模拟上的方法,而不是其他对象。

    而不是在您的代码中这样做:

    string[] lines = new FileWrap().ReadAllLines(filename);
    

    你需要做这样的事情:

    public void MethodThatReadsLines(IFileWrap fileReader) {
        string[] lines = fileReader.ReadAllLines(filename);
    }
    

    这样您就可以从您的测试中注入模拟对象,并由您的生产代码使用,而不是您当前正在使用的新创建的实例:

    [TestMethod()]
    public void Test_this_method()
    {
        IFileWrap fileWrapRepository = MockRepository.GenerateMock<IFileWrap>();
        fileWrapRepository.expect(x => x.ReadAllLines("abc.txt").Return(new string[] {"Line 1", 
                                                                          "Line 2", "Line 3"});
    
        MethodThatReadsLines(fileWrapRepository.Object);
    }
    

    【讨论】:

    • 我应该如何在普通代码中调用 MethodThatReadsLines = 在测试之外?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    相关资源
    最近更新 更多