Quick Tip : Learn by Testing

I have already talked about what to looking for when learning a new programming language. One of the points I brought there was “How do I test my code. Unit testing libraries are available in near every major programming language and are an important tool in the belt!

One way to use unit testing libraries effectively is to use them to give yourself a safe playground for learning other libraries or features of the language.

Say you’re working in the .NET space, and you are trying to learn AutoMapper. One of the easiest ways to try out that library is to spin up a simple unit test project, and test your way into understanding the new framework. Start with simple examples from the docs and assert the values you expect. Try out different functions! Be thorough, and try it all out in the safety of a unit testing project that will not negatively impact your current work.

This has a handy benefit of getting you muscle memory using the library as well.

You can do this for learning programming languages as well. Getting unit tests up and running is a great step in learning a new language, and can be inserted right after the ‘hello world’ step!

Even if you are not a TDD fan, consider starting from scratch with unit testing. Happy coding!

Mocking without Dependencies in F#

I am not a fan of mocking frameworks. Never have been. However, F# allows for some very simple mocking behavior which pretty much throws away the need for mocking frameworks across the board.

Imagine you have the following:

using System;

namespace TestNamespace
{
    public struct Item 
    {
         public string Name { get; set; }
         public double Price { get; set; }
    }

    public interface IDoStuff
    {
          int DoStuffForRealsies(int a, int b, Item y);
    }

    public class ImportantClassToTest
    { 
        public ImportantClassToTest(IDoStuff constructorInjectedDependency)
        {
             /// etc.
        }
    }
}

Depending on your needs, you might choose to make a mock of that IDoStuff interface for testing purposes. Maybe your standard IDoStuff has some database stuff you don’t want running in simple unit tests, or maybe it involves another installed dependency. If you are working in C#, you might be stuck with Moq, or NSubstitute, but in F#, you get a much nicer model.

module WhyFSharpIsBetterV2123

open Xunit
open SampleTestableClasses

let stubDoStuff = { new IDoStuff with 
                            member this.DoStuffForRealsies(a, b, y) = 
                                4
                        }

[<Fact>]
let ``To Heck with Mocking``() =
    let rd = new ImportantClassToTest(stubDoStuff)
    Assert.Equal(2, rd.MethodThatRequiresDi(5))


A nice quick implementation of the interface without any mocking extra dependencies, or any extra libraries to maintain. Just use your F# compiler, unit test library of choice and go.