NancyFx和单元测试Response.AsFile(..)失败,NotFound

本文关键字:失败 NotFound AsFile 单元测试 Response NancyFx | 更新日期: 2023-09-27 18:00:28

这是我的(流线型)模块

public class MyModule : NancyModule
{
    public MyModule() : base("/path")
    {
        Get["/{filename}"] = x =>
        {
            var fileName = (string)x.filename;
            var path = Path.Combine("files", fileName);
            if (!File.Exists(path)) throw new FileNotFoundException();
            return Response.AsFile(path);
        }
    }
}

此代码工作正常,并成功地将正确的文件传递到浏览器。

现在我写了一个测试:

    [TestMethod, DeploymentItem("file.txt", "files")]
    public void CanDownloadFile()
    {
        var path = @"files'file.txt";
        Assert.IsTrue(File.Exists(path));
        var bootstrapper = new MyBootstrapper();
        var browser = new Browser(bootstrapper); // from Nancy.Testing
        var result = browser.Get("/path/file.txt", with =>
        {
            with.HttpRequest();
        });
        var body = result.Body.AsString();
        Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
    }

使用此代码,我的测试失败,因为StatusCode是NotFound而不是OK

我甚至试着用取代Response.AsFile()

var info = new FileInfo(path);
return new GenericFileResponse(info.FullName);

在执行我的测试时,三次检查了文件在磁盘上的物理存在。

怎么了?

NancyFx和单元测试Response.AsFile(..)失败,NotFound

de Solution中是否包含文件"file.txt"?包括此。

在Visual Studio的文件属性中,将"复制到输出目录"属性更改为"复制"(如果更新)。

但您不需要创建一个模块来完成此操作。Yo可以在Nancy引导程序中管理静态内容。这是文件https://github.com/NancyFx/Nancy/wiki/Managing-static-content

这样做,你就不需要测试那个了。