【问题标题】:How can I unit test Nancy modules with F#?如何使用 F# 对 Nancy 模块进行单元测试?
【发布时间】:2016-03-22 10:53:30
【问题描述】:

我正在尝试使用 F# 测试 Nancy 模块,如 here 所述,问题是我看不到如何在 F# 中传递第二个参数。

这是我目前所拥有的:

let should_return_status_ok_for_get() =
    let bootstrapper = new DefaultNancyBootstrapper()    
    let browser = new Browser(bootstrapper, fun req -> req.Accept(new Responses.Negotiation.MediaRange("application/json")))    
    let result = browser.Get("/Menu", fun req ->  req.HttpRequest())
    Assert.AreEqual (HttpStatusCode.OK, result.StatusCode)
    result

在示例中,我应该能够实例化一个 Browser 对象来测试特定的模块:

var browser = new Browser(with => with.Module(new MySimpleModule()));

但我在尝试时在 F# 中遇到编译时错误:

let browser = new Browser(fun req -> req.Module(new MenuModule()))

编辑错误:方法“浏览器”没有重载匹配

在 F# 中有这样的例子吗? 另外,这是在 F# 中解决此问题的最佳方式吗?

【问题讨论】:

  • 错误说明了什么?
  • 很可能你只需要添加 new Browser(Action<_> (fun req -> req.Module ...)) 就可以让它工作 - 遗憾的是,fun 和 Action 之间的转换不如 C# 好(也许你必须帮忙类型而不是 _ 那里)
  • @Carsten,我已经尝试过了,但仍然没有运气。我求助于用 C# 编写浏览器工厂,它只是为我想要的模块返回浏览器。我称之为: let browser = NancyBrowserFactory.Create(); // 直到我在 F# 中对此有足够的了解

标签: unit-testing f# nancy


【解决方案1】:

这就是我在 F# 中运行 Nancy 测试的方式:

我通过从DefaultNancyBootstrapper 派生在我的测试项目中创建一个新的引导程序。我使用这个引导程序来注册我的模拟:

type Bootstrapper() =
    inherit DefaultNancyBootstrapper()

    override this.ConfigureApplicationContainer(container : TinyIoCContainer) =
        base.ConfigureApplicationContainer(container)    
        container.Register<IMyClass, MyMockClass>() |> ignore

然后我编写了一个简单的测试方法来执行 GET 请求,如下所示:

[<TestFixture>]
type ``Health Check Tests`` () =    

    [<Test>]
    member test.``Given the service is healthy the health check endpoint returns a HTTP 200 response with status message "Everything is OK"`` () =
        let bootstrapper = new Bootstrapper()
        let browser = new Browser(bootstrapper)

        let result = browser.Get("/healthcheck")
        let healthCheckResponse = JsonSerializer.deserialize<HealthCheckResponse> <| result.Body.AsString()

        result.StatusCode            |> should equal HttpStatusCode.OK
        healthCheckResponse.Message  |> should equal "Everything is OK"

如果这有帮助,请告诉我!

【讨论】:

  • 因此不可能将浏览器构造函数重载与强类型模块一起使用。我认为这样做会更好,因为您最终也会测试假定的路由
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多