Monday, October 29, 2012

Code Coverage in VS 2012

Code Coverage is a option given for developers to make sure that the tests which they have written covers the code to be tested.
Visual Studio code coverage comes with VS 2012 Test Explorer. It supports both managed & unmanaged Code. Interesting thing is as Test Explorer supports 3rd party unit testing frameworks code coverage also can be used as well. So you can use the Unit test you wish & use Code Converge toll in VS 2012 inbuilt.

1. How to use

once you have run the tests you can right click on the tests in the Test Explorer & click on the on the option “Analyze Code Coverage for Selected Tests”
image
This will show you the code coverage result as below. This result gives you the option to navigate to the code as well. It will show code coverage percentages in following levels
  1. Total Code Coverage
  2. Assembly Level
  3. Class Level
  4. Method Level
image
Once you clicked on any level the text editor in VS will highlight & show you which are the code blocks which have not been covered by the tests written as follows.
image

2. What you prefer Block or Line?

Code Coverage can be counted using Blocks or Lines as you prefer.
  • Block :- A block is a piece of code with exactly one entry and exit point. This will be shown as default in the Code Coverage Results.
  • Lines :- If you prefer to see the Code Coverage by Lines then you can right click on the results & can select ‘Add or remove Column Option’. Then you’ll get tge following window where you can select the columns you want to see in the result set.
image

3. Excluding Elements for Results

If you need to exclude any class, struct, method, property, property setter or getter, event to be exclude from being counted for the code Coverage result VS 2012 gives you that facility as well. All you have to do is following.
1. Add following using statement inside your code.
using System.Diagnostics.CodeAnalysis;
1. Add following attribute to the compenet you want to exclude.
using System.Diagnostics.CodeAnalysis; 
public class CodeCoverageSample
{ 
    [ExcludeFromCodeCoverage]
    void ExampleMethod() {...}// exclude Method 

    [ExcludeFromCodeCoverage] // exclude property
    string  ExampleProperty1 
    { get {...} set{...}}

    int ExampleProperty2
    {
        get
        {
            ...
        }
        [ExcludeFromCodeCoverage] // exclude setter
        set
        {
            ...
        }
    }   }
[ExcludeFromCodeCoverage]
class ExampleClass2 { ... }//exclude class

note:- Excluding a class will not exclude is derived classes from the result set.

To get more details on code coverage customizing you can visit

http://msdn.microsoft.com/en-us/library/jj159530.aspx

4. Using Command Line


To run tests from the command line, use vstest.console.exe. Code coverage is an option of this utility. Open the Visual Studio Developer Command Prompt:


  1. On the Windows Start menu, choose All Programs, Microsoft Visual Studio, Visual Studio Tools, Developer Command Prompt.

  2. Run:
    vstest.console.exe MyTestAssembly.dll /EnableCodeCoverage

Happy Coding !

Microsoft Fakes isolation framework

If you want to isolate the code which you want to create tests from the the code which you don’t Microsoft fake is the solution. By isolation the code being tested make your life easier when identifying where the error is causing when a unit test fails.
Types of “Fakes
Stub :-
Replaces another class with a small substitute that implements the same interface. To use stubs, you have to design your     application so that each component depends only on interfaces, and not on other components. (By "component" we mean a class or group of classes that are designed and updated together and typically contained in an assembly.)
Shim :-
Modifies the compiled code of your application at run time so that instead of making a specified method call, it runs the shim code that your test provides. Shims can be used to replace calls to assemblies that you cannot modify, such .NET assemblies.

When To Use

As a general practice it is recommended to use Stubs for the calls with in your visual studio projects & shims for the referenced Dlls such as system Dll’s. If you have to use shims to isolate the tests which uses the classes with in your projects indicates that your code is badly designed which has not decoupled. We have use shims when we use methods in system Dll’s as they don’t provide interface definitions to override.
Shim Stub
Performance Slow High
Static methods, sealed types Supports only supports to implement interfaces
Internal types Supports Supports
Private methods can replace calls to private methods if all the types on the method signature are visible only replace visible methods
Interfaces and abstract methods Do not Support Supports
Lets see how to use shim & stub for unit test code isolation.

Using Shims

1. Create a class Library & add a Class which contains System.DateTime
public class ShimSample
   {
       public bool UpdateInvoice()
       {
           bool invoiceUpdated = false;
           if (DateTime.Today.Month== 1)
           {
               invoiceUpdated = true;
           }
           return invoiceUpdated;
       }



2. Add new Unit Test Project to your solution & add a test method to test the above method.
3. As System.DateTime is available in System.dll we need to the fake assembly of it to the test project. (note :- this facility is only available in VS2012 Ultimate)
  • Right click on the System under references & click on “Add Fake Assembly”. That’ll add Fake system reference to your test project.
  • Add Shim code inside Shim context. It is required to create Shim context when we use Shims inside our test code to define the lifetime of the shim content.. If we didn’t require this, your shims would last until the AppDomain shut down.
[TestClass]
public class TestShimSample
{
    [TestMethod]
    public void UpdateInvoice()
    {
        // Shims can be used only in a ShimsContext:
        using (ShimsContext.Create())
        {
            // Arrange:
            // Shim DateTime.Now to return a fixed date:
            System.Fakes.ShimDateTime.NowGet =
            () =>
            { return new DateTime(2012, 1, 1); };
            // Instantiate the component under test:
            var componentUnderTest = new ShimSample();
            // Act:
            bool result = componentUnderTest.UpdateInvoice();
            // Assert:
            // This will always be true if the component is working:
            Assert.AreEqual(true, result);
        }
    }
}


Using Stubs

1. First Inject the Interface
In order to use stubs in your tests you have to design your code using dependency injection.. Variables and parameters should be declared by using interfaces and instances of other components should be passed in or created by using a factory.
Here we have defined an interface names IStubSample which will be used in the StubSample class.
public bool ValidateInvoicePrice(IStubSample sample)
{
  int price=  sample.GetInvoicePrice();
  if (price > 0)
  {
      return true;
  }
    else
  {
      return false;
  }
}
 
2. Add the fake Assembly
Add the reference of your project to the test project. Then add the fake assembly of the assembly which contains the interface of that in to the test project. Then create the test as follows.
[TestMethod]
public void TestContosoStockPrice()
{
  // Arrange:
    // Create the fake stockFeed:
    IStubSample stubFeed =
         new VS2012UnitTest.Fakes.IStubSample() // Generated by Fakes.
             {
                 // Define each method:
                 // Name is original name + parameter types:
                 GetInvoicePrice = () => { return 1200; }
             };
    // In the completed application, stockFeed would be a real one:
    var componentUnderTest = new StubSample();
  // Act:
    bool actualValue = ValidateInvoicePrice.GetContosoPrice(stubFeed);
  // Assert:
    Assert.AreEqual(true, actualValue);
}
Hope this gives you idea on fundamentals of fakes in Microsoft unit testing. We’ll discuss on this more details in the future posts.
Happy Fake :)













Saturday, October 27, 2012

Unit Testing in VS 2012

Unit testing is a good software engineering practice which allow developers to assure the quality of the software they development from the beginning. Visual Studio 2012 provides some interesting new features to supports Test driven development mainly for the developers who practice agile practices in their day to day development tasks. In this post I’ll summarize the new features available in VS 2012 in Unit testing & will discuss each feature in detail in the next posts.
  • Test Explorer

    Test Explorer is a powerful tool coming with VS2012 to run the unit tests & view the test results in Visual Studio in a more flexible manner. Test Explorer can be used to mange your test runs of the unit tests which you have written using Microsoft unit testing frameworks for managed and native code and also with the unit tests written using third party & open source unit test frameworks. Visual Studio Extension Manager and the Visual Studio gallery can be used to get these frameworks added. Test Explorer interface provides some useful features to see the test results.
      1. Can filter the test results as we want. ex:- see only the tests which passed
2. Filter tests with matching text using search box facility
3. Can set up to run all the tests after each build for you to verify the quality of the build.
4. You can get the details of the test result of each & every test is being run.
  • Microsoft unit test framework for managed code

    VS 2012 has project Type named Unit Test project which can be used to write unit tests for manages code written in .net framework. Using MS Unit test project type you can write unit test  to analyze & improve the quality of your code. Also VS2012 provides new project type names “Coded UI Unit Test”. This is the automated tests that drive your application through its user interface. These tests will let you verify that the whole application, including its user interface, is functioning correctly. Coded UI Tests are particularly useful where there is validation or other logic in the user interface.
  • Microsoft unit test framework for C++

    One of the main limitations in previous visual studio unit test frameworks is the lack of support for C++ unit testing. VS2012 has overcome this limitation & has improved the level of support for unit test for c++ developers. You can get more details on unit tests on C++ from the following URL: http://msdn.microsoft.com/en-us/library/hh419385.aspx
  • Code coverage tools

    After we write & run the unit tests Code coverage tools in Visual Studio 2012 helps you to determine the proportion of the code being tested in assembly , class & method level. To ensure the quality of the code being released the proportion of the code coverage should be high. Code Coverage Analysis can be used for both manages & unmanaged code. Using code coverage tool you can see the proportion of the code being tested using the source editor. Also this gives you the facility to include and exclude parts of the code from the code coverage analysis as you prefer.
  • Microsoft Fakes isolation framework.

    If you want to isolate the code which you want to create tests from the the code which you don’t Microsoft fake is the solution. By isolation the code being tested make your life easier when identifying where the error is causing when a unit test fails.
    Types of “Fakes
       Stub :-
Replaces another class with a small substitute that implements the same interface. To use stubs, you have to design your     application so that each component depends only on interfaces, and not on other components. (By "component" we mean a class or group of classes that are designed and updated together and typically contained in an assembly.)
       Shim :-
Modifies the compiled code of your application at run time so that instead of making a specified method call, it runs the shim code that your test provides. Shims can be used to replace calls to assemblies that you cannot modify, such .NET assemblies.
http://msdn.microsoft.com/en-us/library/dd537628.aspx
We’ll discuss in details on these topics in the next post.
Happy Coding !!!!

Monday, October 22, 2012

Silverlight with Self hosted WCF with NetTcpBinding

Advantages of using NetTcpBinding

  • Performance: Silverlight applications using NetTcpBinding to with WCF service in your intranet  can obtain a performance gain compared to HTTP polling duplex in duplex communication scenarios.
  • Duplex Communication: Supports Duplex communication between client and service.
  • Helps optimize the Silverlight application (XAP) size. Applications that utilize only

Steps
  1. Create WCF enabling NetTcpBinding


Sample WCF Config,
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="NetTcpWCFService.ServiceBehavior">
          <serviceMetadata />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="NetTcpWCFService "
          name=" NetTcpTest.NetTcpTest ">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration="NetTcpBinding"
            contract="NetTcpTest.INetTcpTestService " />
        <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:4502/NetTcpTestService" />
          </baseAddresses>
        </host>
      </service>

    </services>
    <bindings>
      <netTcpBinding>
        <binding name="NetTcpBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
                  receiveTimeout="00:10:00" sendTimeout="00:01:00"
                  transactionFlow="false" transferMode="Buffered"
                  transactionProtocol="OleTransactions"
                  hostNameComparisonMode="StrongWildcard"
                  listenBacklog="10" maxBufferPoolSize="524288"
                  maxBufferSize="2147483647" maxConnections="10" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
          <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
          <security mode="None"/>
        </binding>
      </netTcpBinding>
    </bindings>
  </system.serviceModel>



 2.    Create Windows Service To Host the WCF



  • ·         Create New Windows Service Project & reference the created WCF dll
  • ·         On Service Start add the following code



  internal static ServiceHost myServiceHost = null;

        protected override void OnStart(string[] args)
        {
         
            if (myServiceHost != null)
            {
                myServiceHost.Close();
            }
            myServiceHost = new ServiceHost(typeof(NetTcpTestService));
            myServiceHost.Open();
        }

This will up the service on windows service start.

  • ·         On Service Stop add the following code to close the WCF service.



  protected override void OnStop()
        {
            if (myServiceHost != null)
            {
                myServiceHost.Close();
                myServiceHost = null;
            }
        } 
3. Create an Outbound rule in machine firewall to open the port which WCF is running. In this case as we have added the base address as "net.tcp://localhost:4502/NetTcpTestService" , open the port ‘4502’






4.       4. Update the clientaccesspolicy file under as follows to C:\inetpub\wwwroot to allow Silverlight    applcations to access the ports enabled.

<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from>
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <socket-resource port="4502-4534" protocol="tcp" />
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>


5      5. Install the Windows service. Then start the windows service under services.
6      6. Then go to the Silverlight project where you want to access the service.
7      7. Right click on references select add service reference. Add the base address in the WCF config to as Address.

You are ready to use the Self hosted WCF with Silverlight.