8. Mocking DataΒΆ

Writing a contract enables you to create a mock server or a client by just writing the Arbitrary instances for datatypes used in the contract.

Lets create a mock server for the contract mentioned in Quick start by writing arbitrary instances for our datatypes.

instance Arbitrary UserData where
    arbitrary = UserData <$> arbitrary
                         <*> arbitrary
                         <*> arbitrary

instance Arbitrary UserToken where
    arbitrary = UserToken <$> arbitrary
                          <*> arbitrary

Now we can create a Wai.Application for our mock server as

mockApp :: Wai.Application
mockApp = mockServer serverSettings (MockServer mockServerSettings)

mockServer takes ServerSettings and MockServer as arguments. MockServer lets you decide what kind of mock data is to be returned (ApiOut, ApiError or OtherError). It returns ApiOut (SuccessData) by default.

Now you can run this Wai.Application on some port to bring up your mock server.

main :: IO ()
main = run 8000 mockApp

You can even mock the requests for the routes. To create a mock Request for route User declared in <Section name here>, we can write:

req <- mockClient (Res :: Resource GET User)

We can use this req while calling client function to make a Request.