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

查看:242
本文介绍了没有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 FormFile 的实例c>是否没有 Moq 框架?

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

推荐答案

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

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天全站免登陆