Skip to content

Instantly share code, notes, and snippets.

@willsam100
Created February 21, 2019 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willsam100/2a449691570dd5f80b38204b50c240f7 to your computer and use it in GitHub Desktop.
Save willsam100/2a449691570dd5f80b38204b50c240f7 to your computer and use it in GitHub Desktop.
Testing parseDomainType
namespace FsharpMvvmCross.Tests
open System
open NUnit.Framework
open FsUnit
open FSharp.Data
open FsharpMvvmCross
[<TestFixture>]
type NoteServiceTests() =
let resposneWithStatusCodeAndBody statusCode body =
{
HttpResponse.Cookies = Map.empty
HttpResponse.Headers = Map.empty
HttpResponse.StatusCode = statusCode
HttpResponse.ResponseUrl = ""
HttpResponse.Body = Text body
}
// helper to create response (using HttpResponse from FSharp.Data)
let successfulResponse body = resposneWithStatusCodeAndBody 200 body
let expectOk f r =
match r with
| Ok x -> f x
| Error e ->
sprintf "Expected OK but got: %A" e |> failwith
let expectError f r =
match r with
| Ok x -> sprintf "Expected Error ParseNote but got: %A" x |> failwith
| Error e -> f e
[<Test>]
member this.``Given a response parseDomainType can parse a list of notes`` () =
successfulResponse """[{"Created":"2019-02-02","Message":"First note"}]"""
|> NotesService.parseDomainType<NotesService.Note list>
|> expectOk (fun result ->
let expected = { NotesService.Created = DateTime(2019, 02, 02); NotesService.Message = "First note" }
result |> List.head |> should equal expected )
[<Test>]
member this.``Given a 500 status code response then we should get back an error with the body as a string`` () =
resposneWithStatusCodeAndBody 500 """[{"Error":"500 internal server error"}]"""
|> NotesService.parseDomainType<NotesService.Note list>
|> expectError (fun result ->
match result with
| NotesService.ServerError s -> s |> should equal """[{"Error":"500 internal server error"}]"""
| e -> failwithf "Expected ServerError s, but got: %A" e )
[<Test>]
member this.``Given a response with a malformed body then the result should be Malfored response`` () =
resposneWithStatusCodeAndBody 200 """malformed JSON"""
|> NotesService.parseDomainType<NotesService.Note list>
|> expectError (fun result ->
match result with
// We do not need to be specific about the exception as this could vary depening on the implementation.
| NotesService.MalformedResponse e -> printfn "%s" e.Message
| e -> failwithf "Expected ServerError s, but got: %A" e )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment