如何为Saturn应用构建集成测试

时间:2019-06-01 11:19:48

标签: f# saturn-framework

我正在尝试为使用Saturn framework构建的小型API构建一些集成测试。

使用常见的Saturn计算表达式构建API,例如applicationcontrollerrouter等。

但是,为了构建集成测试,我认为需要替换application计算表达式(ce)并手工制作一个WebHostBuilder。但是,我该怎么做并将其配置为使用API​​的路由和控制器等?

我的application ce看起来像这样:

let app =
    application {
        url ("http://0.0.0.0:" + port.ToString() + "/")
        use_router apiRouter
        memory_cache
        service_config configureSerialization
        use_gzip
        use_config (fun _ ->
            System.Environment.CurrentDirectory <- (System.Reflection.Assembly.GetExecutingAssembly()).Location
                                                   |> Path.GetDirectoryName
            let configurationRoot =
                ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appSettings.json")
                    .Build()
            let appConfig = FsConfig.AppConfig(configurationRoot)

            let dbPath =
                match appConfig.Get<AppSettings>() with
                | Ok settings when settings.DbConfig.Database.Contains(":memory:") -> settings.DbConfig.Database
                | Ok settings -> Path.Combine(System.Environment.CurrentDirectory, settings.DbConfig.Database)
                | Error _ -> failwithf "Invalid database path"
            { connectionString = dbPath |> sprintf "DataSource=%s;Version=3" })
    } 

使用routercontrollers之一...

let cartController =
    controller {
        create createCartAction
        show getCartAction
        delete deleteCartAction
        subController "/items" cartItemsController
    }

let apiRouter =
    router {
        not_found_handler (setStatusCode 404 >=> text "Not found")
        pipe_through apiPipeline
        forward "/cart" cartController
    }

上面的代码在我的API项目中,下面带有集成测试的代码在第二个项目中。后者具有对前者的项目引用。

let configureApp (app : IApplicationBuilder) =
    app.UseGiraffe(apiRouter) \\<-- This appears to be a problem

let configureServices (services : IServiceCollection) =
    services.AddGiraffe() |> ignore

let builder = WebHostBuilder()
                .UseContentRoot(contentRoot) 
                .Configure(Action<IApplicationBuilder> configureApp)
                .ConfigureServices(configureServices)

let testServer = new TestServer(builder)

let client = testServer.CreateClient()

let! response = client.GetAsync "/"

test <@ HttpStatusCode.OK = response.StatusCode @> 

运行测试时,它将失败,并带有以下异常:

System.InvalidOperationException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'A suitable constructor for type 'Giraffe.Middleware+GiraffeMiddleware' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.' 

问题似乎出在app.UseGiraffe(apiRouter)行上。 apiRouter是在API项目中定义的。

有什么问题吗?

1 个答案:

答案 0 :(得分:0)

事实证明,这与Saturn完全无关。这与F#启动modules的方式有关。 The answer can be found here

如所引用帖子中所建议。我只是添加了一个[<EntryPoint>]函数,一切都按预期工作。