Wednesday 17 August 2022

How to call Private method in Unit test cases in Core Dot Net?

What do you mean by a Unit test ?

 
In the software development process Unit Tests basically test individual parts ( also called as Unit ) of code (mostly methods) and make it work as expected by programmer. A Unit Test is a code written by any programmer which test small pieces of functionality of big programs. Performing unit tests is always designed to be simple, A "UNIT" in this sense is the smallest component of the large code part that makes sense to test, mainly a method out of many methods of some class. 

Generally the tests cases are written in the form of functions that will evaluate and determine whether a returned value after performing Unit Test is equals to the value you were expecting when you wrote the function. The main objective in unit testing is to isolate a unit part of code and validate its to correctness and reliable. 
 
Read more about Unit Test - https://en.wikipedia.org/wiki/Unit_testing
 

Why do we need Unit test?

 
One of the most valuable benefits of using Unit Tests for your development is that it may give you positive confidence that your code will work as you have expected it to work in your development process. Unit Tests always give you the certainty that it will lead to a long term development phase because with the help of unit tests you can easily know that your foundation code block is totally dependable on it.
 
There are few reasons that can give you a basic understanding of why a developer needs to design and write out test cases to make sure major requirements of a module are being validated during testing, 
  • Unit testing can increase confidence and certainty in changing and maintaining code in the development process.
  • Unit testing always has the ability to find problems in early stages in the development cycle.
  • Codes are more reusable, reliable and clean.
  • Development becomes faster.
  • Easy to automate.
  • Read more at - http://agiledata.org/essays/tdd.html

How to call Private method in Unit test cases in Core Dot Net?

First Create a test project and add Private method as shown in below:

Console application:

public class Calculator
{

    private static bool IsPositive(double number)
        {
            return number > 0;
        }
}

Method IsPositive(double number) will check number is Positive or negate and return true or false value.


Create a unit test project and add class "CalculatorTests". Add below codes.

public class CalculatorTests
{
  [TestMethod]
        public void IsPositive_PositiveNumber_ReturnTrue()
        {
            var method = typeof(Calculator).GetMethod("IsPositive", BindingFlags.Static |        BindingFlags.NonPublic);
            bool actual = (bool)method?.Invoke(method, new object[] { 10 });
            Assert.IsTrue(actual);
        }

}


Now run the unit test case. You will get output will Passed.





No comments:

Post a Comment