Thursday, May 18, 2017

Super easy mocking with NSubstitute | Dot Net Recipe

In this post, I will share how to super easy mocking with NSubstitute. First, let's understand the use of mocking and why we need to mock the methods.  In any project, if you are required to write unit test cases then the project is not having any external calls like DataBase or Services then it is easy to write unit test cases, 

Let's understand what is external call, any method call which is not under our project can be called as an external call.

But in real time projects, it's not the case where the project involves at least some external calls it may be DB or other service or something else. 

Any unit test case which you write is required to execute in within the milliseconds, what if it takes more that one minute, then that is the bad practice of writing the unit test cases.

So what's all the point of talking about external calls and unit test case execution performance? I will tell you,

Let's say your unit test case contains any DB call which will get the data for you then that call will take the maximum amount of time in your unit test, so drastically it will reduce the test case execution performance. so you want to eliminate that DB call? 

But from where you get the data here comes the concept of Mocking where you will mock the DB call and return the likewise data which DB will return.

So to mock a method you will need a mechanism, here I am going to explain that mechanism with NSubstitute.


I have created a sample demo project where it will read the student marks from the DB and calculates the percentage of the student. 

So now, I want to write a  test case for the CalculateStudentPercentage Method. You can create Unit test project from "Add New Project"  Window or you can directly "right click" on the method and select "Create Unit Tests",

To use the NSubstitute, firstly you need to install the NSubstitute package

Install-Package NSubstitute

I have the following DataManager.cs Class and Interface IDataManager.cs where it will be used to call the DB and get the results

and I have Processor.cs class where it will have the business logic in your application and you need to write the test cases for the methods which are there in this class. As of now we have one method CalculateStudentPercentage

The only requirement is, we need to have an Interface architecture for your processor so that we can pass NSubstitute to the processor.

Let's write a unit test case for the above method with mocking the DataManager method call using NSubstitute. In the below, we have created a substitute for the IDatamanager and we are returning mockMarksList instead of the original DB Results.

Whenever we have a DB call we are returning the mock data which we have created in the test method. In the below method we have 2 steps
  • Creating an NSubstitute.
  • Invocking the Substitute method and returning the mock data.


Now we have just mocked the GetStudentMarks method and we have returned our mock data instead of the actual data like these you can avoid the external calls. If you any doubts and comments feel free to comment. 

Wednesday, April 26, 2017

Convert Generic List to DataTable using Extension Method

If you want to convert a generic list to DataTable you can use the below extension method for IList<T>

Let's say you have the following list with you 

List<someClass> someClassObjectList = new List<someClass>();

DataTable someDataTable = new DataTable();

and you want to convert the someClassObjectList to DataTable object 

The possible solution you end up by writing a convert or translate method which will convert the each and every property and assigns to DataTable object, something looks like this




By using the above code also your job will get done, but what if your class has 100 properties and what if you want convert lots of different generic lists like this. You can't write the different method for the different generic list, and you don't have the patience to list the 100 properties like above. 

Now what do, you can write a single extension method.

Create a static class in your project with some name like "Extensions" and write the below code in that class

Now in your actual class  wherever you want to convert the generic list to DataTable write code like below

var someDataTable  = someClassObjectList .ToDataTable<someClass>();

using a single method you can convert any generic list to DataTable.

var anotherDataTable  = anotherClassObjectList .ToDataTable<anotherClass>();

var oneMoreDataTable  = oneMoreClassObjectList .ToDataTable<oneMoreClass>();
.
.
.

Write once use anywhere.

Sunday, August 28, 2016

Can Foreach Loop iterates backwards??

Technically speaking the answer is NO, Foreach loop is meant for iterating the list what ever you pass on to it. But to execute the list in backwards using forloop we have different approaches one of the approach is below..

In C# we have Reverse() function which will reverse the list of elements.
Call Reverse() on the list.
Now, iterate using foreach loop that's it your job is doe.

Example:

Class Program
    {
        static void Main(string[] args)
        {
           List<string>  objList =  new List<string>();
           objList.Add("1");
           objList.Add("2");
           objList.Add("3");
         
           objList.Reverse();


           foreach (string obj in objList)
            {
            Console.WriteLine(str.ToString());
             }
    }
Note: This is not efficient way to iterate the list in backwards.

Friday, August 26, 2016

C# Program: Reverse words in a given sentence


To Reverse words in a full of sentence first you would need to split that sentence by space(' ') and create list of strings and push each word by word in to that list. Then  by decrementing the index value of list iterate through the list. Append each string to string builder class and print that string builder object. That's it your done ..!!!

Class Program
    {
        static void Main(string[] args)
        {
            string sample = "My name is string";

            List<string>  smaplestrnigs =  new List<string>();
            smaplestrnigs = sample.Split(' ').ToList();

            StringBuilder str = new StringBuilder();

            for (int i = smaplestrnigs.Count-1; i > -1 ; i-- )
            {
                str.Append(smaplestrnigs[i]);
                str.Append(" ");
            }
            Console.WriteLine(str.ToString());
        }
    }

Output: string is name My