C# xunit测试web api核心文件上传方法
它是WebAPI核心2.1和fileupload方法。我正在使用 Request.Form.Files.FirstOrDefault(); 方法以从客户端获取文件 现在我想用xunit框架编写测试方法。 我该怎么做我想上传文件形式的测试方法,并在网络api控制器。我已经试过了,代码如下。我无法在web api中获取文件C# xunit测试web api核心文件上传方法,c#,core,xunit,C#,Core,Xunit,它是WebAPI核心2.1和fileupload方法。我正在使用 Request.Form.Files.FirstOrDefault(); 方法以从客户端获取文件 现在我想用xunit框架编写测试方法。 我该怎么做我想上传文件形式的测试方法,并在网络api控制器。我已经试过了,代码如下。我无法在web api中获取文件 public class DocumentControllerTest { [Fact] public void TestMethod1
public class DocumentControllerTest
{
[Fact]
public void TestMethod1()
{
DocumentController documentController = new DocumentController();
documentController.ControllerContext = RequestWithFile();
var result = documentController.Upload();
}
private ControllerContext RequestWithFile()
{
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers.Add("Content-Type", "multipart/form
data");
var file = new FormFile(new
MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")), 0, 0,
"Data", "dummy.txt");
httpContext.Request.Form = new FormCollection(new
Dictionary<string, StringValues>(), new FormFileCollection { file
});
var actx = new ActionContext(httpContext, new RouteData(), new
ControllerActionDescriptor());
return new ControllerContext(actx);
}
}
公共类DocumentControllerTest
{
[事实]
公共void TestMethod1()
{
DocumentController DocumentController=新的DocumentController();
documentController.ControllerContext=RequestWithFile();
var result=documentController.Upload();
}
private ControllerContext RequestWithFile()
{
var httpContext=new DefaultHttpContext();
httpContext.Request.Headers.Add(“内容类型”,“多部分/表单
数据);
var file=新的FormFile(新的
MemoryStream(Encoding.UTF8.GetBytes(“这是一个伪文件”)),0,0,
“数据”,“dummy.txt”);
httpContext.Request.Form=新的FormCollection(新的
Dictionary(),新FormFileCollection{file
});
var actx=new ActionContext(httpContext,new RouteData(),new
ControllerActionDescriptor());
返回新的ControllerContext(actx);
}
}