Skip to content

Instantly share code, notes, and snippets.

@lessismore1
Forked from nakamura-to/gist:4316660
Created February 17, 2019 03:49
Show Gist options
  • Save lessismore1/24e587eb2cd1fc5dc49695bcf228f843 to your computer and use it in GitHub Desktop.
Save lessismore1/24e587eb2cd1fc5dc49695bcf228f843 to your computer and use it in GitHub Desktop.
ASP.NET Web API Test in F#
open System
open System.Collections.Generic
open System.Net
open System.Net.Http
open System.Web.Http
open System.Web.Http.Dispatcher
open System.Web.Http.SelfHost
open Microsoft.VisualStudio.TestTools.UnitTesting
open Newtonsoft.Json.Linq
open Newtonsoft.Json.Serialization
open WebApi
type defaults = { id: RouteParameter }
[<TestClass>]
type PersonControllerTest() =
let baseAddress = new Uri("http://localhost:9090/")
let config = new HttpSelfHostConfiguration(baseAddress);
[<TestInitialize>]
member this.Initialize() =
config.Routes.MapHttpRoute(
name = "Default",
routeTemplate = "api/{controller}/{id}",
defaults = { id = RouteParameter.Optional })
|> ignore
config.IncludeErrorDetailPolicy <- IncludeErrorDetailPolicy.Always;
config.Services.Replace(typeof<IAssembliesResolver>,
{ new IAssembliesResolver with
member this.GetAssemblies() =
[| typeof<PersonController>.Assembly |] :> ICollection<_> })
let jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.ContractResolver <- new CamelCasePropertyNamesContractResolver()
[<TestMethod>]
member this.TestGet() =
async {
use server = new HttpSelfHostServer(config)
do! Async.AwaitTask <| server.OpenAsync().ContinueWith(fun _ -> ())
use client = new HttpClient(BaseAddress = baseAddress)
use! response = Async.AwaitTask <| client.GetAsync("api/person")
let! content = Async.AwaitTask <| response.Content.ReadAsStringAsync()
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, content)
let result = JArray.Parse(content)
Assert.AreEqual(2, result.Count)
let person = result.[0]
Assert.AreEqual("hoge", string person.["name"])
Assert.AreEqual(10, int person.["age"])
let person = result.[1]
Assert.AreEqual("foo", string person.["name"])
Assert.AreEqual(20, int person.["age"]) }
|> Async.RunSynchronously
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment