在我对代码进行单元测试的过程中,我有以下代码:
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);下面是我从不同站点收集到的测试结果:
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(),所以请告诉我单元测试有什么问题。
发布于 2015-04-28 21:12:08
//Suppose we have this setup
public class MyClass
{
string ReturnSomething()
{
return "FooBar";
}
void DoSomething(out string reason){
reason = 'Oops';
}
}NSubstitute常用的顽固性语法是像这样使用Returns:
myClass.ReturnSomething().Returns("wibble");这个存根去掉了ReturnSomething(),但是Returns语法只适用于具有返回值的方法。
对于没有返回的方法,我们可以使用When().Do()。这基本上是指文档中的Action (相对于具有返回值的Func )。这样做的一个共同需要是填写这些方法的输出参数:
string reason;
myClass.When(c => c.DoSomething(out reason))
.Do(args =>
{
args[0] = "Fail";
});有关Action和Func的更多信息,请参见MSDN:动作,漏斗。
在单元测试的特定情况下,不要在调用saved时设置变量SaveAs,而是考虑使用NSubstitute.Received结构进行断言。
https://stackoverflow.com/questions/29929670
复制相似问题