我正在尝试为使用Saturn 框架构建的小型 API 构建一些集成测试。
API 是使用常用的计算表达式构建的,例如Saturn
,application
等。controller
router
但是为了构建集成测试,我需要替换application
计算表达式 (ce) 并手工制作WebHostBuilder
.
我的application
ce 看起来像这样:
module Server
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" })
}
带有一个router
和controllers
...
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(Server.apiRouter) \\<-- The problem is here. Server.apiRouter is null!
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(Server.apiRouter)
。apiRouter
是在 API 项目的模块中定义的Server
——但是当这段代码在测试项目中运行时Server.apiRouter
是null
.
但是,如果我将测试代码移动到与 - 测试代码相同的项目中,API
则测试工作完美。
如果从测试项目中调用 apiRouter
计算表达式,为什么会这样?null