In the previous article we have seen how to unit test private instance methods. In this article we will see unit testing static private methods. If you have not read the previous article on unit testing private instance methods, I would strongly recomend you to read, before you proceed with this article. In general, to unit test a static public method, we invoke the respective method using the In the example below, CalculatePower() is a private static method. The purpose of this method is to calculate the value, when a given number is raised to a certain power. For example 2 to the power of 3 should return 8 and 3 to the power of 2 sholuld return 9. So to unit test this method we create the instance of PrivateType class. To the constructor of the PrivateType class we pass the type of the class that contains the private static method that we want to unit test. We do this by using the typeof keyword. The PrivateType instance can then be used to invoke the private static method that is contained with in the Maths class. The Maths class that contains the static private CalculatePower() method and the unit test are shown below. public class Maths { private static int CalculatePower(int Base, int Exponent) { int Product = 1; for (int i = 1; i <= Exponent; i++) { Product = Product * Base; } return Product; } } [TestMethod()] public void CalculatePowerTest() { PrivateType privateTypeObject = new PrivateType(typeof(Maths)); object obj = privateTypeObject.InvokeStatic("CalculatePower", 2, 3); Assert.AreEqual(8, (int)obj); } |
Unit Testing a private static method in C# .NET
Subscribe to:
Post Comments (Atom)
How do we pass information from one form to another?
ReplyDeleteThere are several ways to send data from one web form to another. Please refer to the article below. Pass information from one form to another
ReplyDeleteVenkat can u brief access accessifier..Please
ReplyDeleteWe can control the scope of the member object of a class using access specifiers
ReplyDeletethere are many types of access specifiers
1-Public ,its can access from any where of class
2-private,it can access only inside the class
3-The scope of accessibility is limited within the class or struct and the class derived (Inherited )from this class.
4-internal ,The internal access modifiers can access within the program that contain its declarations and also access within the same assembly level but not from another assembly.
5-Protected internal, Protected internal is the same access levels of both protected and internal. It can access anywhere in the same assembly and in the same class also the classes inherited from the same class .
noce post... it is clear and easily understood...keep going sir
ReplyDeletethanks for sharing sir... it was clear..
ReplyDeleteWhat is boxing and unboxing? Please explain with example in details. I have lots of problem in this.
ReplyDelete