Sunday 14 October 2018

Create a Unit Test Case in C# using Moq

In this post we are going to see how to create a unit test case in C# using Moq. First we create a library project and write the following code.

public interface ICalculator
    {
       (string operation, int result) DoOperation(string operation, int a, int b);
    }


    public class Calculator:ICalculator
    {
        public (string operation,int result) DoOperation(string operation,int a,int b)
        {
            (string operation, int result) operationResult;
            int c = 0;
            switch (operation)
            {
                case "add":
                    c = a + b;
                    break;
                case "sub":
                    c = a - b;
                    break;
                case "mul":
                    c = a * b;
                    break;
                default:
                    c = a + b;
                    break;
            }
            operationResult =(operation, c);
            return operationResult;
        }
    }

public class CalMachine
    {
        private ICalculator calc;

        public CalMachine():this(new Calculator())
        {

        }

        public CalMachine(ICalculator obj)
        {
            this.calc = obj;
        }

       public (string operation, int result) Operate(string operationType, int a , int b)
        {
            return calc.DoOperation(operationType, a, b);
        }

    }


Now create a unit test case project and add the reference of library project to the unit test case project
Then install the Moq using nuget package manager. Mock the interface and pass that object to the instance. Then setup the method DoOperation, where the method mock and returns the response which has mentioned in the Returns

[TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            // Arrange
            Moq.Mock<ICalculator> cal = new Moq.Mock<ICalculator>();
         cal.Setup(x => x.DoOperation(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))                                        .Returns(("add", 3));
            CalMachine machine = new CalMachine(cal.Object);

            // ACT
            (string operation, int result) result = machine.Operate("add", 1, 3);

            // Assert
            Assert.AreEqual("add", result.operation);
            Assert.AreEqual(3, result.result);
        }
    }



From this code you can learn how to write a unit test case for c# project using Moq. 

Saturday 13 October 2018

How to create named tuples in c#

In this post we are going to see how to use the named tuples in C#, Previously when you use the Tuple it will result in showing the values are like Item1, Item2 etc, instead of resemble Item1 and Item2 if we want to name the items, we can do that using the named tuple.


Syntax for named tuple declaration:
(string operation, int result) operationResult;

Let we see a sample like calculator.

public interface ICalculator
    {
       (string operation, int result) DoOperation(string operation, int a, int b);

    }




    public class Calculator:ICalculator
    {
        public (string operation,int result) DoOperation(string operation,int a,int b)
        {
            (string operation, int result) operationResult;
            int c = 0;
            switch (operation)
            {
                case "add":
                    c = a + b;
                    break;
                case "sub":
                    c = a - b;
                    break;
                case "mul":
                    c = a * b;
                    break;
                default:
                    c = a + b;
                    break;
            }
            operationResult =(operation, c);
            return operationResult;
        }
    }

When you see return type of the method DoOperation, it is named tuple

public class CalMachine
    {
        private ICalculator calc;

        public CalMachine():this(new Calculator())
        {

        }

        public CalMachine(ICalculator obj)
        {
            this.calc = obj;
        }

        public (string operation, int result) Operate(string operationType, int a , int b)
        {
            return calc.DoOperation(operationType, a, b);
        }

    }




Main Program

CalMachine cmachine = new CalMachine();
var aresult = cmachine.Operate("add", 1, 2);
Console.WriteLine($"Operation: {aresult.operation}, Result: {aresult.result}");

When you see the main program in the console writeline we are accessing the value from named Tuple based on variable name;

From this post you can see how to create the named Tuples in C#

Thursday 20 September 2018

How to solve Operator '==' cannot be applied to operands of type 'T'

In this post we are going to see how to compare a field or property which have type as T Generic. Generally if you try to compare Generic types with ==,!= operator it will results in Operator == or != cannot be applied to operands of Type 'T'

For example:
********************

  public class Node<T>
    {
        private T _data;
        private Node<T> _next;
        private Node<T> _prev;

        public T Data
        {
            get { return _data; }
            set { _data = value; }
        }

        public Node<T> Next
        {
            get { return _next; }
            set { _next = value; }
        }

        public Node<T> Previous
        {
            get { return _prev; }
            set { _prev = value; }
        }

        public Node(T value):this(value,null, null)
        {
           
        }

        public Node(T value, Node<T> next, Node<T> prev)
        {
            this._data = value;
            this._next = next;
            this._prev = prev;
        }
    }


public Node<T> AddBefore(Node<T> element, T value)
   {
            var tempNode1 = new Node<T>(value);
            var tempNode2 = new Node<T>(value);

            if(tempNode1.Data == tempNode2.Data) { 
              
            }
         
   } 


In the above example if you see the line , if(tempNode1.Data == tempNode2.Data) { where we compare the two T type with == operator now this will return a compile time error.

To resolve this error we have to use EqualityComparer

if(EqualityComparer<T>.Default.Equals(tempNode1.Data,tempNode2.Data))

{

}


so the result method will be
public Node<T> AddBefore(Node<T> element, T value)
{
            var tempNode1 = new Node<T>(value);
            var tempNode2 = new Node<T>(value);

            if(EqualityComparer<T>.Default.Equals(tempNode1.Data,tempNode2.Data)) { 
              
            }
         


From this post you can learn how to solve operator '==' cannot be applied to operands of type 'T'

Sunday 16 September 2018

Singleton deisgn pattern in c# Lazy and Eager initialization

In this post we are going to see how to create a singleton class in eager and lazy initialization concepts in c#

Key things to remember for singleton is
1. Private constructor
2. Static Property to get the instance
3. Backing field should be readonly static
4.  Singleton class should be sealed

Lazy Initialization
*************************
First we create lazy initialization of singleton class

public sealed class EmployeeSingleton
    {
        private static readonly Lazy<EmployeeSingleton> _instance = new
                    Lazy<EmployeeSingleton>(() => new EmployeeSingleton());

        private EmployeeSingleton() { }

        public static EmployeeSingleton Instance
        {
            get
            {
                return _instance.Value;
            }
        }

        public void Log(string message)
        {
            Console.WriteLine(message);
        }


    }



Eager Initialization
**************************

    public sealed class DepartmentSingleton
    {
        private static readonly DepartmentSingleton _instance = new
                                             DepartmentSingleton();

        private DepartmentSingleton()
        {

        }

        public static DepartmentSingleton Instance
        {
            get
            {
                return _instance;
            }
        }

        public void Log(string message)
        {
            Console.WriteLine(message);
        }

    }


Main program:
**************

static void Main(string[] args)
        {
            EmployeeSingleton obj1 = EmployeeSingleton.Instance;
            DepartmentSingleton obj2 = DepartmentSingleton.Instance;

            obj1.Log("test 1");
            obj2.Log("test 2");

            Console.Read();


        }

From this post you can learn how to create a singleton design pattern in c# lazy and eager initialization.