How to Mock in C# using NSubstitute

In Java when we had to test our application using Mocking then we use PowerMockito.Refer below on how to use it
http://thebadengineer.com/powermockito-for-mocking-and-testing/

In C# if we have to Mock and test our application then we use NSubstitute.To add and install NSubstitute in the project
Refer the official page : https://nsubstitute.github.io/help/getting-started/

Here We will discuss some basic operation using NSubstitute and Mock and test our Application.

namespace sample.test
{
    public interface IKustoCon
    {
        List<QueryItem> ExecuteQuery(string query, List<string> fieldNames);
    }
}

namespace sample.test2
{
	 public class KustoConnectionManager : IKustoCon
    {
    	 public List<QueryItem> ExecuteQuery(string query,
                                            List<string> fieldNames)
        {
            try{
            //code for which you want to implement
            }catch(Exception e)
            {
            
            }
        }
        
       public void Run()
       {
         List<String> queryItems = new List<String>();
         queryItems.Add("sample");
         var result = ExecuteQuery("sample",queryItems);
       }
    }
}

Now above code shows two class in which KustoConnectionManager inherits from IKustoCon..
If I want to return my own list from executeQuery method I can Mock the object of the interface and return my own value from the function as given below:

namespace Test
{
    public class SampleTest{
       private IKustoCon _ikustoCon;
    }
   
   [TestInitialize]
   public void Initialize()
   {
   _ikustoCon = Substitute.For<IKustoCon>();
   }
  
   [TestCleanup]
   public void cleanup()
   {
   //cleanup code
   }
  
  [TestMethod]
  [TestCategory("BillingMonitorTest")]
  public void TestMethod()
   {
       List<String> queryItems = new List<String>();
       queryItems.Add("ABC");
       queryItems.Add("ABC");
       _ikustoCon.ExecuteQuery(Arg.Any<string>(), fileNames).ReturnsForAnyArgs(queryItems);
       KustoConnectionManager kustoConnectionManager = new KustoConnectionManager();
       kustoConnectionManager.Run();
   }
}
//Now in the Run Method whenever ExecuteQuery Method is called it will return queryItems defined in the TestMethod()

I will upload more sample cases to make it clear 🙂