模拟 File.OpenWrite() [英] Mocking File.OpenWrite()

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

问题描述

我正在尝试编写一个单元测试,该测试将写入使用 File.OpenWrite() 打开的文件.

I'm trying to write a unit test that writes to a file it opens with File.OpenWrite().

我正在使用 SystemWrapper 的 IFileWrap 接口包装文件.在生产中,我使用 SimpleInjector 注入 SystemWrapper 的 FileWrap 类的一个实例,并且工作正常.但我试图在我的单元测试中模拟 IFileWrap,使用 MOQ,但这是行不通的.

I'm wrapping File with SystemWrapper's IFileWrap interface. In production, I'm using SimpleInjector to inject an instance of SystemWrapper's FileWrap class, and that's working fine. But I'm trying to mock IFileWrap in my unit tests, using MOQ, and that's not working.

我是 SystemWrapper 的新手,我正在尽最大努力弄清楚它的用途.据我所知,IFileWrap.OpenWrite() 返回一个 IFileWrap 实例,您可以从中获取带有 FileStreamInstance 的流.

I'm new to SystemWrapper, and I'm doing my best to figure out how it is intended to be used. As far as I can tell, IFileWrap.OpenWrite() returns an IFileWrap instance, from which you can obtain the stream with FileStreamInstance.

因此,在我测试的类中,我在构造函数中注入了一个 IFileWrap:

So, in my class under test, I inject an IFileWrap in my constructor:

public class ClassUnderTest
{
    private readonly IFileWrap fileWrap;

    public ClassUnderTest(IFileWrap fileWrap)
    {
        this.fileWrap = fileWrap;
    }

    ...
}

在我测试的方法中,我从 FileStreamInstance 获取流:

And in my method under test, I get the stream from FileStreamInstance:

var fsWrap = this.fileWrap.OpenWrite(fullPath);
var ostream = fswrap.FileStreamInstance;

这在生产中工作正常,其中 fileWrap 使用 FileWrap 实例进行实例化.但是在我的测试中,我正在尝试为File.OpenWrite 返回一个模拟的 FileStream:

That works fine, in production, where fileWrap is instantiated with an instance of FileWrap. But in my tests, I'm trying to create a Mock for File.OpenWrite that returns a mocked FileStream:

var fileStreamMock = new Mock<IFileStreamWrap>();

var fileMock = new Mock<IFileWrap>();
fileMock.Setup(fm => fm.OpenWrite(It.IsAny<string>())).Returns(fileStreamMock.Object);

var classUnderTest = new ClassUnderTest(fileMock.Object);

当我在调试器中遍历测试中的方法时,从我的单元测试中,fsWrap.FileStreamInstance 为空,而我希望它是我的模拟文件流.

And when I walk through the method under test, in the debugger, from my unit test, fsWrap.FileStreamInstance is null, when I'd expect it to be my mocked filestream.

对我做错了什么有任何想法吗?

Any ideas as to what I am doing wrong?

推荐答案

您不会存根 FileStreamInstance 返回任何内容,因此 Moq 将返回 null.

You're not stubbing FileStreamInstance to return anything, so Moq will return null.

在创建 IFileStreamWrap 模拟后,您需要设置为 FileStreamInstance 返回一些内容:

You need to set up to return something for FileStreamInstance after creating your IFileStreamWrap mock:

var fileStreamWrapMock = new Mock<IFileStreamWrap>(); // Was fileStreamMock
var fileStreamMock = new Mock<FileStream>();
fileStreamWrapMock.Setup(fswm => fswm.FileStreamInstance).Returns(fileStreamMock);

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

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