加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用OpenFileDialog c#的单元测试文件读取方法

发布时间:2020-12-15 23:38:45 所属栏目:百科 来源:网络整理
导读:我有一个函数,它返回文本文件路径和文件内容: public static Tuplestring,string OpenTextFile(){ OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog .Filter = "Text |*.txt"; bool? accept = openFileDialog.ShowDialog(); if (acce
我有一个函数,它返回文本文件路径和文件内容:

public static Tuple<string,string> OpenTextFile()
{
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog .Filter = "Text |*.txt";

    bool? accept = openFileDialog.ShowDialog();

    if (accept == true)
        return Tuple.Create(File.ReadAllText(openFileDialog.FileName,Encoding.UTF8),openFileDialog.FileName);
    else
        return null;
}

我如何单元测试文件读取?是否可以测试对话框显示?

解决方法

该方法与多个问题紧密相关. OpenFileDialog是一个UI问题,File是一个IO问题.这使得单独测试该方法的功能变得困难但并非不可能.

将这些问题提取到他们自己的抽象中.

public interface IOpenFileDialog {
    string Filter { get; set; }
    bool? ShowDialog();
    string FileName { get; set; }
}


public interface IFileSystem {
    string ReadAllText(string path,Encoding encoding = Encoding.UTF8);
}

我还建议将该静态方法转换为服务方法

public interface ITextFileService {
    Tuple<string,string> OpenTextFile();
}

它的实现将取决于其他抽象

public class TextFileService : ITextFileService {
    readonly IOpenFileDialog openFileDialog;
    readonly IFileSystem file;

    public SUT(IOpenFileDialog openFileDialog,IFileSystem file) {
        this.openFileDialog = openFileDialog;
        this.file = file;
    }

    public Tuple<string,string> OpenTextFile() {
        openFileDialog.Filter = "Text |*.txt";

        bool? accept = openFileDialog.ShowDialog();

        if (accept.GetValueOrDefault(false))
            return Tuple.Create(file.ReadAllText(openFileDialog.FileName,openFileDialog.FileName);
        else
            return null;
    }
}

然后,依赖关系的实现将包含它们各自的关注点.

这也将允许在单独测试其家属时模拟/替换所有抽象.

以下是基于上述建议使用MSTest和Moq测试方法的示例.

[TestMethod]
public void _OpenTextFile_Should_Return_TextContext_And_FileName() {
    //Arrange
    var expectedFileContent = "Hellow World";
    var expectedFileName = "filename.txt";

    var fileSystem = new Mock<IFileSystem>();
    fileSystem.Setup(_ => _.ReadAllText(expectedFileName,It.IsAny<Encoding>()))
        .Returns(expectedFileContent)
        .Verifiable();

    var openFileDialog = new Mock<IOpenFileDialog>();
    openFileDialog.Setup(_ => _.ShowDialog()).Returns(true).Verifiable();
    openFileDialog.Setup(_ => _.FileName).Returns(expectedFileName).Verifiable();

    var sut = new TextFileService(openFileDialog.Object,fileSystem.Object);


    //Act
    var actual = sut.OpenTextFile();

    //Assert
    fileSystem.Verify();
    openFileDialog.Verify();
    Assert.AreEqual(expectedFileContent,actual.Item1);
    Assert.AreEqual(expectedFileName,actual.Item2);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读