What is Unit Testing?

Unit Testing is a very important part of coding. It consumes time and efforts, but it worth it. Thanks to Unit Testing you will feel more confident and you will know that your code is working. Of course testing everything is almost impossible, but at least the normal cases and some specific exceptions to represent what your methods should do and how they should behave.

What is mocking in a Unit Test?

The concept of mocking is to create an abstraction of something. Let’s say you want to test how your Business Logic behaves in some cases, but you don’t want to pollute your database with test data, that’s where mocking takes place. In this case, you could mock your Data Layer and still test the Business Logic.

What is MOQ?

MOQ is a mocking library made for your Unit Tests. MOQ is intended to be simple to use, strongly typed (no magic strings, and therefore full compiler-verified and refactoring-friendly) and minimalistic (while still fully functional). With MOQ you can simulate the input parameters and the results returned by your method.

How to mock with MOQ?

In a previous post, I explained how to mock Directory.GetFiles(). Long story short, here is a simple example of how to do it:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using MockFiles;
using Moq;
using System.Collections.Generic;

namespace UnitTests
    public class UnitTest1
        private IDirectoryHelper _directoryHelper;
        private readonly string _file1 = "test1.txt";
        private readonly string _file2 = "test2.txt";

        public void Initialize()
            _directoryHelper = Mock.Of<IDirectoryHelper>();

                .Setup(x => x.GetFiles(It.IsAny<string>()))
                .Returns((string x) =>
                    new List<string>

        public void GetFiles_Test()
            ICollection<string> files = _directoryHelper.GetFiles(@"C:\");

            Assert.IsTrue(files.Count == 2);
Code language: C# (cs)

This article explained why Unit Testing is a fundamental part of coding and why mocking with MOQ simplifies our Unit Tests.

Happy coding! 🙂