4 Comments
  •   Posted in: 
  • F#

titleImage

In this post I want to look at how to get started with Unit Testing while developing F#. I’m usually writing my code in C# and prefer to write my code in a TDD fashion, just to be on the safe side and sleep sound during the nights Winking smile In  my last blog post I looked at how to create a Web API service with F# and ended up testing the controller manually via a browser. So lets look how we can extend that solution to provide an automated way to test the controller.

Adding a test project

I’ll be using xUnit to create my tests. To get started you will just need a standard F# .Net Library (do not choose a Portable Class Library i.e. PCL). Then via NuGet add the following package:

PM> Install-Package xunit -Version 2.0.0

To be able to test the controller we must also add the FSharpWebSample project to the References. Now we can start writing tests as for example we can see in CarsControllerTest.fs:

namespace FSharpWebSample.Test
open Xunit
open FSharpWebSample.Controllers

module CarsControllerTest =

    let carsController = new CarsController()

    [<Fact>]
    let Get_WhenInvoked_ReturnsAListContainingMultipleElements() = 
        let cars = carsController.Get()
        Assert.False(cars.IsEmpty)

    [<Fact>]
    let GetWithIndex_WhenInvokedWithAValidIndex_ReturnsASingleItem() = 
        let car = carsController.Get(2)
        Assert.True(car.Id = 2)

Ensure that the xUnit and Controllers namespace is referenced in the test class:

open Xunit
open FSharpWebSample.Controllers

Running the tests

We can use the Test Explorer from Visual Studio run our tests as the xUnit runner NuGet package will make the xUnit tests visible to it. Simply add the package to the test project:

PM> Install-Package xunit.runner.visualstudio -Version 2.0.1
Then we can run the tests via Test, Runand finally All Tests. After executing our tests we get the all green.

Showing test runner after executing the tests.

Conclusion

In this post we saw how Unit Tests can be created for and executed to ensure our code is running correctly. Which reduces the load on manual testing and ensures that single code blocks work within expected parameters.

You can find the entire project on GitHub.

0 Comments

In this post I want to look at how to create a Web API project with F# and host it on Azure. This will part of a blog series on how to create a mobile application (incl. the backend) based on F#. The blog post assumes that you the reader has a basic understanding of how to create a Web API web service.

F# is a functional programming language based on the .Net Framework which contrary to many other functional programming languages also makes it a general purpose language. In my endeavor to explore a functional programming language I chose F# as it will allow me to create not only .Net applications but also Xamarin based cross platform apps.

To deploy to Azure you will need a valid Azure account. Alternatively you can run the App on your local machine.

Setting up the project

I’ll be using Visual Studio 2015 RC for this setup but you can follow along on VS 2013 just as well. Create a new project then go to Online projects, Select Visual F# and then select F# MVC 5. This only has to be done during the first setup. From now on you will find the project template under the Installedproject templates.

NewProjectFromOnlineTemplate

Having a look at the solution

If you are familiar with a Web API solution you will find yourself right at home.

WebApiSolution

Under Controllers you find the expected definitions, as well as under models. The Global.asax.fs also has a familiar ring to it:

namespace FSharpWebSample

open System
open System.Net.Http
open System.Web
open System.Web.Http
open System.Web.Routing

type HttpRoute = {
    controller : string
    id : RouteParameter }

type Global() =
    inherit System.Web.HttpApplication() 

    static member RegisterWebApi(config: HttpConfiguration) =
        // Configure routing
        config.MapHttpAttributeRoutes()
        config.Routes.MapHttpRoute(
            "DefaultApi", // Route name
            "api/{controller}/{id}", // URL with parameters
            { controller = "{controller}"; id = RouteParameter.Optional } // Parameter defaults
        ) |> ignore

        // Configure serialization
        config.Formatters.XmlFormatter.UseXmlSerializer <- true
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver <- Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()

        // Additional Web API settings

    member x.Application_Start() =
        GlobalConfiguration.Configure(Action<_> Global.RegisterWebApi)

Extending the Controller

When we look at the controller we see that an array of the model is created and there is on method that will return the list. Let’s extend the controller to return a value requested by it’s Id. So first we have to extend the model Car.fs:

namespace FSharpWebSample.Models

open Newtonsoft.Json

[<CLIMutable>]
type Car = {
    Make : string
    Model : string
    Id : int
}

Now we can extend the CarsController.fs so that we can filter the list and get the according value:

namespace FSharpWebSample.Controllers
open System
open System.Collections.Generic
open System.Linq
open System.Net.Http
open System.Web.Http
open FSharpWebSample.Models

/// Retrieves values.
type CarsController() =
    inherit ApiController()
    
    let values = [ { Make = "Ford"; Model = "Mustang"; Id = 1 }; { Make = "Nissan"; Model = "Titan"; Id = 2 }; { Make = "Audi"; Model = "R8"; Id = 3 } ]
    
    /// Gets all values.
    member x.Get() = values
    
    member x.Get(id:int) = values |> List.filter(fun v -> v.Id = id)

Deploying to Azure

Deploying to azure luckily is luckely the same as it always has been for C#, right click onto the Web API project, select Publish…, Microsoft Azure Web Apps then create a new web app enter a name and finally click on Pubish. Now all that is left is to test the web service so lets do this the manual way.

Testing the controller

Opening the prefered browser of your choice e.g. the new Edge browser enter the path to the azure website and be executing the following URI:

http://fsharpwebsample.azurewebsites.net/api/cars

We receive the entire list:

[{"make":"Ford","model":"Mustang","id":1},{"make":"Nissan","model":"Titan","id":2},{"make":"Audi","model":"R8","id":3}]

When we add a Id parameter:

http://fsharpwebsample.azurewebsites.net/api/cars/3

We only receive the requested record:

[{"make":"Audi","model":"R8","id":3}]

Conclusion

Creating a Web API service with F# is not much different than creating it with C# thanks to Ryan Riley and Daniel Mohl who provide the F# MVC 5 template. Also uploading it to Azure and sending requests are the way one would expect the service to run. Looking forward to go on further down the F# rabbit hole.

You can find the sample on GitHub.