如何在没有 Moq 的情况下在 C# 中实例化 FormFile 的实例? [英] How to instantiate an instance of FormFile in C# without Moq?

查看:42
本文介绍了如何在没有 Moq 的情况下在 C# 中实例化 FormFile 的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个函数,该函数通过集成测试将文件附加到 RavenDB 数据库中的文档.为此,我需要一个 IFormFile 实例.

I want to test a function that attaches files to documents in a RavenDB database with an integration test. For this, I need an instance of IFormFile.

显然,我无法从接口实例化,因此我尝试实例化 FormFile 继承自 IFormFile 接口.

Obviously, I can't instantiate from an interface so I tried to instantiate an instance of FormFile which inherits from the IFormFile interface.

using (var stream = File.OpenRead("placeholder.pdf"))
{
    var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
    {
        ContentType = "application.pdf"
    };
}

但这会引发以下错误:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.AspNetCore.Http.Internal.FormFile.set_ContentType(String value)

当我从代码中删除 ContentType = "application.pdf" 时,它允许我实例化一个新实例,但没有 ContentType.

When I remove the ContentType = "application.pdf" from the code it allows me to instantiate a new instance but without a ContentType.

如何使用 ContentType 而没有 Moq 框架来实例化 FormFile 的实例?

How do I instantiate an instance of FormFile with the ContentType and without the Moq framework?

推荐答案

感谢 Hans 的评论,实际答案是:

Thanks to Hans his comment, the actual answer is:

using (var stream = File.OpenRead("placeholder.pdf"))
{
    var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
    {
        Headers = new HeaderDictionary(),
        ContentType = "application/pdf"
    };
}

这篇关于如何在没有 Moq 的情况下在 C# 中实例化 FormFile 的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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