Can you unit test a private method? How do you do it?

The answer is No. We cannot unit test a private method.

  • Unit Tests are designed to test the functionalities of components which are exposed to other components for consumption.
  • Private methods are designed to hide functionality from the other components as a part of data abstraction.
  • So its not a good practice to try unit testing a private method.
  • We can instead try unit testing a public method which calls this private method and assert the overall expectation.

What are extension methods? When do you use them?

  • Extension methods help extending types without altering them
  • They're particularly useful for extending classes which are sealed
  • They're created as static methods inside static classes
  • The first parameter of the extension methods is the type for which the method is to extend.
  • If the return type of the extension method is the type they're extending, then the methods can be chained together.
public class MyClass {
  /// 
}

public static MyClassExtensions {
  public static MyClass DoExtended(this MyClass obj, int someparam1, int someparam2.. )
  {
      // do something
      return obj;
  }
}


MyClass obj = new MyClass();
obj.DoExtended(); // this works although DoExtended is not a part of MyClass

What is closure in Javascript?

  • In Javascript, a closure can be imagined as a concept of a function scope within a function.
  • The global execution context can be treated as a whole function in which all the script contents are present, and when we run the script the global function is called.
(function () {
    let k = 1;
    function kd() {
        console.log(`value of k is ${k}`);
    }
    kd();
})();

output:
value of k is 1
  • the inner functions present in this function can access all the variables that are defined in the outer scope and can modify them.
  • interestingly, these variables are still available even after the outer function has been executed and removed from memory.
function outer() {
    let counter = 0;
    function inner() {
        counter++;
        return counter;
    }
    return inner;
}

let instance = outer();
console.log(instance());
console.log(instance());
console.log(instance());

output:
1
2
3
  • In the above code block, the outer function is called only once, while when we call the inner function multiple times the variable counter which is native to the outer function is modified by the inner function and value persists.
  • This is conceptually similar to the context of methods and properties in a class where the methods can access and modify the variables of the class in an Object Oriented Language.