Monthly Archives: March 2019

Perfect console application in .net Core: add unit tests

Unit test are crucial part in software development process. In late 1990s Kent Beck stated that writing tests is the most important part of writing software in ExtremeProgramming metodology. You can read a bit more about it in Martins Fowler article.

This is a part of a series of articles about writing a perfect console application in .net core 2. Feel free to read more:

My example

To have a simple example how to add tests to .net core console application I created a TicketStore app. It is a console app to reserve tickets in cinema. It’s structure looks like this:

Here is how command handling looks like:

    command = Console.ReadLine();
    if (!_commandValidator.IsValid(command))
    {
        Console.WriteLine($"Sorry, command: '{command}' not recognized.");
    }

And CommandValidator looks like this:

As you noticed validator contains regular expression and parsing logic, that can always be faulty. We only allow a column to be from A to H and seat to be between 1 and 15. Let’s add unit test to be sure that it works that way.

Adding tests project

Adding a test project

Project name that I would like to test is MichalBialecki.com.TicketStore.Console so I need to add a class library with name
MichalBialecki.com.TicketStore.Console.Tests.

Adding unit tests packages

To write unit tests I’m adding my favourite packages:

  • NUnit – unit test framework
  • NUnit3TestAdapter – package to run tests
  • NSubstitute – mocking framework
  • Microsoft.NET.Test.Sdk – it’s important to remember about this one, tests would not run without it

Now we can start writing tests.

First test

I added a CommandValidatorTests and now my project structure looks like this:

And test looks like this.

    using MichalBialecki.com.TicketStore.Console.Helpers;
    using NUnit.Framework;

    [TestFixture]
    public class CommandValidatorTests
    {
        private CommandValidator _commandValidator;

        [SetUp]
        public void SetUp()
        {
            _commandValidator = new CommandValidator();
        }

        [TestCase("A1", true)]
        [TestCase("A15", true)]
        [TestCase("A11", true)]
        [TestCase("H15", true)]
        [TestCase("H16", false)]
        [TestCase("K15", false)]
        [TestCase("I4", false)]
        [TestCase("K.", false)]
        [TestCase("", false)]
        [TestCase(null, false)]
        public void IsValid_GivenCommand_ReturnsExpectedResult(string command, bool expectedResult)
        {
            // Arrange & Act
            var result = _commandValidator.IsValid(command);

            // Assert
            Assert.AreEqual(expectedResult, result);
        }
    }

In Resharper unit tests sessions window all tests passed.

Notice how test results are shown – everything is clear from the first sight. You can immidiately see what method is tested and with what conditions.

If you’re interested what are the best practices to write unit tests, have a look at my article: https://www.michalbialecki.com/2019/01/03/writing-unit-tests-with-nunit-and-nsubstitute/. It will guide you through the whole process and clearly explaining best practices.

  All code posted here you can find on my GitHub: https://github.com/mikuam/console-app-net-core

 

Perfect console application in .net Core: set up dependency injection

It may seem that when creating a console application we are doomed to use statics all over the code. Well.. we’re not! I’ll show you how to set up dependency injection and use it.

This is a part of a series of articles about writing a perfect console application in .net core 2. Feel free to read more:

Dependency Injection

There are many packages that can provide dependency injection, but I chose SimpleInjector, because I know it well. It’s also quite fast, according to Daniel Palme’s article. Here is how whole calss looks like:

    using System.Linq;

    using SimpleInjector;

    public static class ContainerConfig
    {
        private static Container Container;

        public static void Init()
        {
            Container = new Container();

            RegisterAllTypesWithConvention();

            Container.Verify();
        }

        public static TService GetInstance<TService>() where TService : class
        {
            return Container.GetInstance<TService>();
        }

        private static void RegisterAllTypesWithConvention()
        {
            var typesWithInterfaces = typeof(Program).Assembly.GetExportedTypes()
                .Where(t => t.Namespace.StartsWith("MichalBialecki.com.TicketStore"))
                .Where(ts => ts.GetInterfaces().Any() && ts.IsClass).ToList();
            var registrations = typesWithInterfaces.Select(ti => new
                {
                    Service = ti.GetInterfaces().Single(), Implementation = ti
                });

            foreach (var reg in registrations)
            {
                Container.Register(reg.Service, reg.Implementation, Lifestyle.Singleton);
            }
        }
    }

Notice RegisterAllTypesWithConvention method – it is the way to register all interface implementations, that follows a simple naming convention. When interface will have an additional I in the name comparing to it’s class implementation, then it will be automatically registered. No need to remember about such silly things now!

No more statics in .net core all over the code 🙂

 All code posted here you can find on my GitHub: https://github.com/mikuam/console-app-net-core