如何模拟StreamWriter [英] how to mock StreamWriter

查看:66
本文介绍了如何模拟StreamWriter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试以下

//将输出值写入文件

I need to test the following

// Write the output value to file

使用 ( streamWriter = StreamWriter (filePath))

{

using (StreamWriter streamWriter = new StreamWriter(filePath))

{

streamWriter.Write(Actual.InnerXml.ToString());

streamWriter.Write(Actual.InnerXml.ToString());

}

文件路径是磁盘上的实际路径,如果找不到文件路径,则测试失败.我认为我需要模拟StreamWriter.有人可以帮忙吗?我正在使用Rhino Mock.

}

The filepath is an actual path on the disk, if it does not find the file path it fails the test. I think i will need to mock the StreamWriter. Can any one please help? I am using Rhino Mock.

推荐答案

您从哪里获得filePath变量?  是否可以将其注入到方法或类中(也许作为方法参数或类属性)?

Where do you get the filePath variable from?  Is there a way you can inject that into your method or class (perhaps as a method parameter or class property)?

然后,您可以将filePath的值更改为某个无效路径,例如"C:\ tempFake \ myReallyfakeFile.txt".

Then you could just change the value of filePath to some invalid path, like "C:\tempFake\myReallyfakeFile.txt".

例如:

public void ReadMyFile(string filePath)
{
    using (StreamWriter sw = new StreamWriter(filePath))
    {
        sw.Write(Actual.InnerXml.ToString());
    }
}

然后您的单元测试将类似于:

And then your unit test would be something like:

[TestMethod]
[ExpectedException(typeof(IOException))]
public void TestReadMe_InvalidFile_ThrowsError()
{
    string fakePath = @"C:\tempFake\myReallyFakeFile.txt";

    MyClass.ReadMyFile(fakePath);
}


这篇关于如何模拟StreamWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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