首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSubstitute HttpPostedFileBase SaveAs

NSubstitute HttpPostedFileBase SaveAs
EN

Stack Overflow用户
提问于 2015-04-28 20:50:55
回答 1查看 310关注 0票数 1

在我对代码进行单元测试的过程中,我有以下代码:

代码语言:javascript
复制
        var ufile = Substitute.For<HttpPostedFileBase>();
        var server = Substitute.For<HttpServerUtilityBase();
        var saved = false;
        ufile.FileName.Returns("somefileName"); 
        var fileName = fs.Path.GetFileName(ufile.FileName);
        var path = fs.Path.Combine(server.MapPath(upath), fileName);
        ufile.When(h => h.SaveAs(path)).Do(x => saved = true);
        Assert.IsTrue(saved);

下面是我从不同站点收集到的测试结果:

代码语言:javascript
复制
public ActionResult UploadFiles()
    {
        var fileinfo = new List<UploadedImageViewModel>();

        foreach (string files in Request.Files)
        {
            var hpf = Request.Files[files] as HttpPostedFileBase; // 
            if (hpf != null && hpf.ContentLength > 0)
                continue;
            var FileName = Path.GetFileName(hpf.FileName); //Gets name of file uploaded
            var temppath = Path.Combine(Server.MapPath("~/uploadtemp/"), FileName); // creates a string representation of file location
            hpf.SaveAs(temppath);
            //resize the image before you save it to the right folder under FileUploads

        }
        return View(fileinfo);
    }

当().Do()语法时,有人能帮助我理解这一点吗?在文档中,它说do应该有一个动作,但是我需要一些例子来理解。

然后,HttpPostedFileBase的SaveAs()方法是无效的,在Nsubstitute中,它要求对void方法使用when().Do(),所以请告诉我单元测试有什么问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-28 21:12:08

代码语言:javascript
复制
//Suppose we have this setup
public class MyClass
{
    string ReturnSomething() 
    {
        return "FooBar";
    }

    void DoSomething(out string reason){
        reason = 'Oops';
    }
}

NSubstitute常用的顽固性语法是像这样使用Returns

代码语言:javascript
复制
myClass.ReturnSomething().Returns("wibble");

这个存根去掉了ReturnSomething(),但是Returns语法只适用于具有返回值的方法。

对于没有返回的方法,我们可以使用When().Do()。这基本上是指文档中的Action (相对于具有返回值的Func )。这样做的一个共同需要是填写这些方法的输出参数:

代码语言:javascript
复制
string reason;
myClass.When(c => c.DoSomething(out reason))
    .Do(args => 
    {
        args[0] = "Fail";
    });

有关Action和Func的更多信息,请参见MSDN:动作漏斗

在单元测试的特定情况下,不要在调用saved时设置变量SaveAs,而是考虑使用NSubstitute.Received结构进行断言。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29929670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档