正在尝试模拟上传文件。
这是控制器端
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(@"c:\work\",
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";这是单元测试端
[TestMethod]
public void TestMethod()
{
Mock<ControllerContext> cc = new Mock<ControllerContext>();
HomeController c = new HomeController()
{
ControllerContext = cc.Object
};
c.ControllerContext.RouteData = new RouteData();
UTF8Encoding enc = new UTF8Encoding();
Mock<HttpPostedFileBase> file1 = new Mock<HttpPostedFileBase>();
var server = new Mock<HttpServerUtilityBase>();
file1.SetupGet(d => d.FileName).Returns("listebv.txt");
MemoryStream ms = new MemoryStream(enc.GetBytes(@"C:\work\listebv.txt"));
file1.SetupGet(d => d.InputStream).Returns( ms);
file1.SetupGet(d => d.ContentLength).Returns((int)ms.Length);
file1.SetupGet(d => d.ContentType).Returns("text/plain");
cc.SetupGet(d => d.HttpContext.Request.Files.Count).Returns(1);
cc.SetupGet(d => d.HttpContext.Request.Files[0]).Returns(file1.Object);
c.Index(file1.Object);当我启动测试时,file.SaveAs (path)不工作(没有创建文件),也没有返回错误
有什么想法吗?
发布于 2018-03-16 23:01:05
您正在传递一个模拟对象。该模拟对象实际上并不保存文件。您应该检查一下是否使用期望值在mock上调用了SaveAs。
file1.Verify(f => f.SaveAs(@"c:\work\listebv.txt"));https://stackoverflow.com/questions/49323750
复制相似问题