While this will be a short post it’s also one that may be one of the most important ones to go over – running unit tests. Most of you probably know that being able to run tests early and often can save a ton of time if issues are found later on. One way to do this is to be able to execute your tests as easy as possible and this is possible within your FAKE script. Once again, FAKE comes with functions to be able to execute our tests in any framework you may be using.

Building the Unit Test Project

Of course, before running our tests we need to build the project. As we’ve seen in the previous posts, we’ll build the project with the MsBuild function.

let testProj = !! "FakeDemo.UnitTests/FakeDemo.UnitTests.csproj"

Target "Build-UnitTests" (fun _ ->
    testProj
        |> MSBuild "FakeDemo.UnitTestsbinDebug" "Build" [ ("Configuration", "Debug"); ("Platform", "Any CPU") ]
        |> Log "---Unit Test build output----"
)

Executing Unit Tests

Now here is another cool thing I really like from FAKE – they include helper functions that execute the tests for us. All we need to do is to pass in some configuration and we’re good to go!

let testDll = !! "FakeDemo.UnitTests/bin/Debug/FakeDemo.UnitTests.dll"

Target "Run-UnitTests" (fun _ ->
    testDll |> NUnit ( fun defaults -> 
        { 
            defaults with ToolPath = "/Library/Frameworks/Mono.framework/Commands/"
                          ToolName = "nunit-console4" 
                          WorkingDir = "FakeDemo.UnitTestsbinDebug"
                          DisableShadowCopy = true
        })
)

Test Execution

Of course, FAKE will definitely report if any tests have failed.

Test Failed

FAKE doesn’t do this with just NUnit, though, as I briefly mentioned in the beginning of this post. It has similar functions for a few of the main unit testing frameworks, including XUnit, MSTest, and even SpecFlow tests. All of these other testing framework functions work basically the same as above.

Using Target Build Orders

If you may recall in our first part of this series we briefly touched on creating target build orders. When running tests, this can be quite helpful as it allows you to run the test target and it will do all the cleaning and building that it needs before running the tests. Have a look at the build order we have in this script.

"Clean"
  ==> "Build-Pcl"
  ==> "Build-iOS"
  ==> "Build-Droid"
  ==> "Run-UnitTests"

If we run our script as ./build "Run-UnitTests" it will start running the Clean target and continue down the chain until Run-UnitTests completes.

In our next post, we’ll take a look at using FAKE to run our Xamarin UI tests. Until then, the complete code for this post is available on GitHub.


Need Xamarin Help?

Xamarin Consulting  Xamarin Training