Sunday, 27 March 2016

Delegates and Event

Delegates have a few capabilities in C#: referencing methods, Dispatching multiple methods, asynchronous execution and event typing.

public delegate double Add(double num1, double num2);

A Delegate is just like a class , struct and interfaces. and its default access modifier is public and internal only.

Firing Events:
Events are type members that allows a type to notify other types of things that have happened.

A Button class, which is typically supplied by the UI technology you’re using.
2. An event member of the Button class, named Clicked.
3. The UI technology takes care of knowing when that Clicked event should fire. I’ll use a SimulateClick method in an upcoming code listing.
4. The event has a delegate type. Only methods that conform to the signature of that delegate type can assign to this delegate.
5. Your code defines a method to be called when that event fires.
6. The method you write must have a signature that matches the delegate type of the event. If the method signature doesn’t match the event delegate type signature, the compiler won’t let you assign that method to the delegate.


Basically, a delegate is just a wrapper around what would be a function pointer in C (or a list of function pointers)

An event is an even higher level abstraction that wraps the concept of a delegate together with methods to subscribe and unsubscribe a method to such delegates.
An event is a “property” that exposes an add and remove method (invoked via += and -= in code) to add/remove subscribers to a delegate list.

An event is a notification mechanism, based on delegates. The only thing it exposes publicly is a pair of methods (add/remove) to subscribe to or unsubscribe from the notification. A delegate type is used to define the signature of the handler methods, and the list of subscribers are (usually) stored internally as a delegate.

An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.

"Suppose events didn't exist as a concept in C#/.NET. How would another class subscribe to an event?
Three options:
  1. public delegatevariable
  2. delegate variable backed by a property
  3. delegate variable with AddXXXHandler and RemoveXXXHandler methods
Option 1 is clearly horrible, for all the normal reasons we abhor public variables.
Option 2 is better, but allows subscribers to effectively override each other - it would be all too easy to write someInstance.MyEvent = eventHandler; which would replace any existing event handlers rather than adding a new one. In addition, you still need to write the properties.
Option 3 is basically what events give you, but with a guaranteed convention (generated by the compiler and backed by extra flags in the IL) and a "free" implementation if you're happy with the semantics that field-like events give you. Subscribing to and unsubscribing from events is encapsulated without allowing arbitrary access to the list of event handlers, and languages can make things simpler by providing syntax for both declaration and subscription."


to understand the differences you can look at this 2 examples
Exemple with Delegates (Action in this case that is a kind of delegate that doen't return value)
public class Animal
{
    public Action Run {get; set;}

    public void RaiseEvent()
    {
        if (Run != null)
        {
            Run();
        }
    }
}
to use the delegate you should do something like this
Animale animal= new Animal();
animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running") ;
animal.RaiseEvent();
this code works well but you could have some weak spots.
For example if I write this
animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running");
animal.Run = () => Console.WriteLine("I'm sleeping") ;
with the last line of code I had override the previous behaviors just with one missing + (I have used = instead of +=)
Another weak spot is that every class that use your Animal class can raise RaiseEvent just calling it animal.RaiseEvent().
To avoid this weak spots you can use events in c#.
Your Animal class will change in this way
public class ArgsSpecial : EventArgs
{
    public ArgsSpecial (string val)
    {
        Operation=val;
    }

    public string Operation {get; set;}
} 

public class Animal
{
    // Empty delegate. In this way you are sure that value is always != null 
    // because no one outside of the class can change it.
    public event EventHandler<ArgsSpecial> Run = delegate{} 

    public void RaiseEvent()
    {  
         Run(this, new ArgsSpecial("Run faster"));
    }
}
to call events
 Animale animal= new Animal();
 animal.Run += (sender, e) => Console.WriteLine("I'm running. My value is {0}", e.Operation);
 animal.RaiseEvent();
Differences:
  1. You aren't using a public property but a public field (with events the compiler protect your fields from unwanted access)
  2. Events can't directly be assigned. In this case you can't do the previous error that I have showed with overriding the behavior.
  3. No one outside of your class can raise the event.
  4. Events can be included in an interface declaration, whereas a field cannot
notes
EventHandler is declared as the following delegate:
public delegate void EventHandler (object sender, EventArgs e)
it takes a sender (of Object type) and event arguments. The sender is null if it comes from static methods.
You can use also EventHAndler instead this example that use EventHandler<ArgsSpecial>
refer here for documentation about EventHandler

How to Write Integration Test for Web API

I’ll give just an idea of what integration tests are and how can we write it. Integration tests doesn’t run in memory. For WebAPI’s the best practice to write integration test is when the WebAPI is self hosted.You can try writing integration test when you host an API, so that you you get an actual URL or endpoint of the service you want to test.The test is performed on actual data and actual service. Let’s proceed with an example. I have hosted my web api and I want to test GetAllProducts() method of WebAPI.My hosted URL for the particular controller action is http://localhost:50875/v1/Products/Product/allproducts.
Now I know that I am not going to test my controller method through dll reference but I want to actually test its endpoint for which I need to pass an authentication token because that end point is secured and can not be authorized until I add a secure token to the Request header. Following is the integration test forGetAllProducts().
[Test]
public void GetAllProductsIntegrationTest()
{
    #region To be written inside Setup method specifically for integration tests
        var client = new HttpClient { BaseAddress = new Uri(ServiceBaseURL) };
        client.DefaultRequestHeaders.Add("Authorization", "Basic YWtoaWw6YWtoaWw=");
        MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
        _response = client.PostAsync("login", null).Result;

        if (_response != null && _response.Headers != null && _response.Headers.Contains("Token") && _response.Headers.GetValues("Token") != null)
        {
        client.DefaultRequestHeaders.Clear();
        _token = ((string[])(_response.Headers.GetValues("Token")))[0];
        client.DefaultRequestHeaders.Add("Token", _token);
        }
    #endregion

    _response = client.GetAsync("v1/Products/Product/allproducts/").Result;
    var responseResult =
    JsonConvert.DeserializeObject<List<ProductEntity>>(_response.Content.ReadAsStringAsync().Result);
    Assert.AreEqual(_response.StatusCode, HttpStatusCode.OK);
    Assert.AreEqual(responseResult.Any(), true);
}
I have used same class to write this test, but you should always keep your unit tests segregated from integration tests, so use another test project to write integration tests for web api. First we have to request a token and add it to client request,
var client = new HttpClient { BaseAddress = new Uri(ServiceBaseURL) };
client.DefaultRequestHeaders.Add("Authorization", "Basic YWtoaWw6YWtoaWw=");
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
_response = client.PostAsync("login", null).Result;

if (_response != null && _response.Headers != null && _response.Headers.Contains("Token") && _response.Headers.GetValues("Token") != null)
{
client.DefaultRequestHeaders.Clear();
_token = ((string[])(_response.Headers.GetValues("Token")))[0];
client.DefaultRequestHeaders.Add("Token", _token);
}
In above code I have initialized the client with running service’s base URL i.e. http://localhost:50875. After initialization I am setting a default request header to call my login endpoint of Authentication controller to fetch valid token.Once the user logs in with his credentials he get a valid token. To read in detail about security refer my article on security in web api. I have passed base 64 string of my credentials username :Akhil and password:Akhil for basic authentication. Once request gets authenticated, I get a valid token in _response.Headers that I fetch and assign to _token variable and add to client’s default header with this line of code,
_token = ((string[])(_response.Headers.GetValues("Token")))[0];
client.DefaultRequestHeaders.Add("Token", _token);
Then I am calling the actual service URL from the same client,
_response = client.GetAsync("v1/Products/Product/allproducts/").Result;

Unit Test with WebAPI

[TestMethod]
    public void Uri_ValidFormatTest()
    {
        var requestMock = new Mock<IRequestClient>();            
        var client = new RestClient(requestMock.Object);

        string address = "https://www.google.co.nz";
        string postData = "method=payment&params[Key1]=Value1&params[Key2]=Value2&params[Key3]=Value3";

        requestMock.Setup(x => x.UploadString(new Uri(address), postData)).Returns("Success");

        Assert.AreEqual("Success", client.MakeRequest(address, postData));
    }

[Test]
public void GetAllProductsTest()
{
    var productController = new ProductController(_productService)
        {
        Request = new HttpRequestMessage
            {
            Method = HttpMethod.Get,
            RequestUri = new Uri(ServiceBaseURL + "v1/Products/Product/all")
            }
        };
    productController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());

    _response = productController.Get();

    var responseResult = JsonConvert.DeserializeObject<List<Product>>(_response.Content.ReadAsStringAsync().Result);
    Assert.AreEqual(_response.StatusCode, HttpStatusCode.OK);
    Assert.AreEqual(responseResult.Any(), true);
    var comparer = new ProductComparer();
    CollectionAssert.AreEqual(
    responseResult.OrderBy(product => product, comparer),
    _products.OrderBy(product => product, comparer), comparer);
}
et me explain the code step by step. We start by creating an instance of ProductController and initialize the Request property of the controller with new request message stating calling http method as GET and initialize theRequestUri with base hosted service URL and appended with actual end point of the method. InitializingRequestUri is not necessary in this case but will help you if you test actual service end point. In this case, we are not testing actual endpoint but the direct controller method.
HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() line adds defaulthttpconfiguration to HttpConfigurationKey necessary for controller instance instantiation.
_response = productController.Get(); line calls the Get() method of controller that fetches all the products from dummy _products list. Since the return type of the method was an http response message, we need to parse it to get the JSON result sent from the method. All the transactions from API’s should ideally happen in the form of JSON or XML only. This helps the client to understand the response and its result set. We de-serialize the object we got from _response using NewtonSoft library into a list of products. That means the JSON response is converted to List<Product> for better accessibility and comparison. Once done with JSON to List object conversion, I have put three asserts to test the result.
Assert.AreEqual(_response.StatusCode, HttpStatusCode.OK); line checks the http status code of the response, the expected is HttpStatusCode.OK.
Second assert i.e. Assert.AreEqual(responseResult.Any(), true); checks that we have got the items in the list or not. Third assert is the actual confirmation assert for our test that compares each product from the actual product list to the returned product list.
image

Saturday, 26 March 2016

MOQ Framework

MOQ framework uses to write unit test for .Net Frmaework application.

Moq is intended to be simple to use, strong typed (no magic strings!, and therefore full compiler-verified and refactoring-friendly) and minimalistic (while still fully functional!).

Methods

using Moq;

// Assumptions:
public interface IFoo {
   public bool DoSomething(string);
   public bool TryParse(string, out string));
}

var mock = new Mock<IFoo>();
mock.Setup(foo => foo.DoSomething("ping")).Returns(true);


// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);


// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);


// access invocation arguments when returning a value
mock.Setup(x => x.DoSomething(It.IsAny<string>()))
        .Returns((string s) => s.ToLower());
// Multiple parameters overloads available


// throwing when invoked
mock.Setup(foo => foo.DoSomething("reset")).Throws<InvalidOperationException>();
mock.Setup(foo => foo.DoSomething("")).Throws(new ArgumentException("command"));


// lazy evaluating return value
mock.Setup(foo => foo.GetCount()).Returns(() => count);


// returning different values on each invocation
var mock = new Mock<IFoo>();
var calls = 0;
mock.Setup(foo => foo.GetCountThing())
    .Returns(() => calls)
    .Callback(() => calls++);
// returns 0 on first invocation, 1 on the next, and so on
Console.WriteLine(mock.Object.GetCountThing());

Matching Arguments

// any value
mock.Setup(foo => foo.DoSomething(It.IsAny<string>())).Returns(true);


// matching Func<int>, lazy evaluated
mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true); 


// matching ranges
mock.Setup(foo => foo.Add(It.IsInRange<int>(0, 10, Range.Inclusive))).Returns(true); 


// matching regex
mock.Setup(x => x.DoSomething(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");

Properties

mock.Setup(foo => foo.Name).Returns("bar");


// auto-mocking hierarchies (a.k.a. recursive mocks)
mock.Setup(foo => foo.Bar.Baz.Name).Returns("baz");

// expects an invocation to set the value to "foo"
mock.SetupSet(foo => foo.Name = "foo");

// or verify the setter directly
mock.VerifySet(foo => foo.Name = "foo");
  • Setup a property so that it will automatically start tracking its value (also known as Stub):
// start "tracking" sets/gets to this property
mock.SetupProperty(f => f.Name);

// alternatively, provide a default value for the stubbed property
mock.SetupProperty(f => f.Name, "foo");


// Now you can do:

IFoo foo = mock.Object;
// Initial value was stored
Assert.Equal("foo", foo.Name);

// New value set which changes the initial value
foo.Name = "bar";
Assert.Equal("bar", foo.Name);
  • Stub all properties on a mock (not available on Silverlight):
    mock.SetupAllProperties();

Events

// Raising an event on the mock
mock.Raise(m => m.FooEvent += null, new FooEventArgs(fooValue));

// Raising an event on a descendant down the hierarchy
mock.Raise(m => m.Child.First.FooEvent += null, new FooEventArgs(fooValue));

// Causing an event to raise automatically when Submit is invoked
mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, EventArgs.Empty);
// The raised event would trigger behavior on the object under test, which 
// you would make assertions about later (how its state changed as a consequence, typically)

// Raising a custom event which does not adhere to the EventHandler pattern
public delegate void MyEventHandler(int i, bool b);
public interface IFoo
{
  event MyEventHandler MyEvent; 
}

var mock = new Mock<IFoo>();
...
// Raise passing the custom arguments expected by the event delegate
mock.Raise(foo => foo.MyEvent += null, 25, true);

Callbacks

var mock = new Mock<IFoo>();
mock.Setup(foo => foo.Execute("ping"))
    .Returns(true)
    .Callback(() => calls++);

// access invocation arguments
mock.Setup(foo => foo.Execute(It.IsAny<string>()))
    .Returns(true)
    .Callback((string s) => calls.Add(s));

// alternate equivalent generic method syntax
mock.Setup(foo => foo.Execute(It.IsAny<string>()))
    .Returns(true)
    .Callback<string>(s => calls.Add(s));

// access arguments for methods with multiple parameters
mock.Setup(foo => foo.Execute(It.IsAny<int>(), It.IsAny<string>()))
    .Returns(true)
    .Callback<int, string>((i, s) => calls.Add(s));

// callbacks can be specified before and after invocation
mock.Setup(foo => foo.Execute("ping"))
    .Callback(() => Console.WriteLine("Before returns"))
    .Returns(true)
    .Callback(() => Console.WriteLine("After returns"));

Verification

mock.Verify(foo => foo.Execute("ping"));

// Verify with custom error message for failure
mock.Verify(foo => foo.Execute("ping"), "When doing operation X, the service should be pinged always");

// Method should never be called
mock.Verify(foo => foo.Execute("ping"), Times.Never());

// Called at least once
mock.Verify(foo => foo.Execute("ping"), Times.AtLeastOnce());

// Verify getter invocation, regardless of value.
mock.VerifyGet(foo => foo.Name);

// Verify setter invocation, regardless of value.
mock.VerifySet(foo => foo.Name);

// Verify setter called with specific value
mock.VerifySet(foo => foo.Name ="foo");

// Verify setter with an argument matcher
mock.VerifySet(foo => foo.Value = It.IsInRange(1, 5, Range.Inclusive));

Customizing Mock Behavior

  • Make mock behave like a "true Mock", raising exceptions for anything that doesn't have a corresponding expectation: in Moq slang a "Strict" mock; default behavior is "Loose" mock, which never throws and returns default values or empty arrays, enumerables, etc. if no expectation is set for a member
    var mock = new Mock(MockBehavior.Strict);
  • Invoke base class implementation if no expectation overrides the member (a.k.a. "Partial Mocks" in Rhino Mocks): default is false. (this is required if you are mocking Web/Html controls in System.Web!)
    var mock = new Mock { CallBase = true };
  • Make an automatic recursive mock: a mock that will return a new mock for every member that doesn't have an expectation and whose return value can be mocked (i.e. it is not a value type)
    var mock = new Mock<IFoo> { DefaultValue = DefaultValue.Mock };
    // default is DefaultValue.Empty
    
    // this property access would return a new mock of IBar as it's "mock-able"
    IBar value = mock.Object.Bar;
    
    // the returned mock is reused, so further accesses to the property return 
    // the same mock instance. this allows us to also use this instance to 
    // set further expectations on it if we want
    var barMock = Mock.Get(value);
    barMock.Setup(b => b.Submit()).Returns(true);
  • Centralizing mock instance creation and management: you can create and verify all mocks in a single place by using a MockFactory, which allows setting the MockBehavior, its CallBase and DefaultValue consistently
    var factory = new MockFactory(MockBehavior.Strict) { DefaultValue = DefaultValue.Mock };
    
    // Create a mock using the factory settings
    var fooMock = factory.Create<IFoo>();
    
    // Create a mock overriding the factory settings
    var barMock = factory.Create<IBar>(MockBehavior.Loose);
    
    // Verify all verifiable expectations on all mocks created through the factory
    factory.Verify();

Miscellaneous

  • Setting expectations for protected members (you can't get intellisense for these, so you access them using the member name as a string):
    // at the top of the test fixture
    using Moq.Protected;
    
    // in the test
    var mock = new Mock<CommandBase>();
    mock.Protected()
         .Setup<int>("Execute")
         .Returns(5);
    
    // if you need argument matching, you MUST use ItExpr rather than It
    // planning on improving this for vNext
    mock.Protected()
        .Setup<string>("Execute",
            ItExpr.IsAny<string>())
        .Returns(true);

Advanced Features

// get mock from a mocked instance
IFoo foo = // get mock instance somehow
var fooMock = Mock.Get(foo);
fooMock.Setup(f => f.Submit()).Returns(true);


// implementing multiple interfaces in mock
var foo = new Mock<IFoo>();
var disposableFoo = foo.As<IDisposable>();
// now the IFoo mock also implements IDisposable :)
disposableFoo.Setup(df => df.Dispose());

//implementing multiple interfaces in single mock
var foo = new Mock<IFoo>();
foo.Setup(f => f.Bar()).Returns("Hello World");
foo.As<IDisposable>().Setup(df => df.Dispose());


// custom matchers
mock.Setup(foo => foo.Submit(IsLarge())).Throws<ArgumentException>();
...
public string IsLarge() 
{ 
  return Match.Create<string>(s => !String.IsNullOrEmpty(s) && s.Length > 100);
}
  • Mocking internal types of another project: add the following assembly attribute (typically to the AssemblyInfo.cs) to the project containing the internal types:
    // This assembly is the default dynamic assembly generated Castle DynamicProxy, 
    // used by Moq. Paste in a single line.   
    [assembly:InternalsVisibleTo("DynamicProxyGenAssembly2,PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]

Note: when you need to pass the mock for consumption, you must use the mock.Object accessor as a consequence of a C# compiler restriction (vote to get it removed at Microsoft Connect)
Note2: above link is currently dead. Last checked 2016-01-23. Also, what is the restriction? The note above piques curiosity.

Linq to Mocks

Moq is the one and only mocking framework that allows specifying mock behavior via declarative specification queries. You can think of Linq to Mocks as:
from the universe of mocks, get me one/those that behave like this (by Fernando Simonazzi)
Keep that query form in mind when reading the specifications:
var services = Mock.Of<IServiceProvider>(sp =>
    sp.GetService(typeof(IRepository)) == Mock.Of<IRepository>(r => r.IsAuthenticated == true) &&
    sp.GetService(typeof(IAuthentication)) == Mock.Of<IAuthentication>(a => a.AuthenticationType == "OAuth"));

// Multiple setups on a single mock and its recursive mocks
ControllerContext context = Mock.Of<ControllerContext>(ctx =>
     ctx.HttpContext.User.Identity.Name == "kzu" &&
     ctx.HttpContext.Request.IsAuthenticated == true &&
     ctx.HttpContext.Request.Url == new Uri("http://moqthis.com") &&
     ctx.HttpContext.Response.ContentType == "application/xml");

// Setting up multiple chained mocks:
var context = Mock.Of<ControllerContext>(ctx =>
     ctx.HttpContext.Request.Url == new Uri("http://moqthis.me") &&
     ctx.HttpContext.Response.ContentType == "application/xml" &&
     // Chained mock specification
     ctx.HttpContext.GetSection("server") == Mock.Of<ServerSection>(config =>
         config.Server.ServerUrl == new Uri("http://moqthis.com/api"));
Linq to Mocks is great for quickly stubbing out dependencies that typically don't need further verification. If you do need to verify later some invocation on those mocks, you can easily retrieve them with Mock.Get(instance).