New Unit Test functionality in VS2012 Update 2: Test Playlist

In VS2012 we have support for basically any Unit Test Framework, because the new test runner is plugin based, and everyone can write plugin to make it compatible with the framework of choice. From the original version that was released with Visual Studio 2012 RTM, in Update 1 and Update 2 the test runner gained a lot of new feature, really useful for everyday work.

Update 2 introduced the concept of “Test Playlist”: basically a simple tool to create a subset of Unit Tests that are meant to be managed together. Since Update 1 already introduced the concept of Traits to group tests, this feature can be seen as a duplicate, but traits and playlist have different meaning. Let’s see how to create a playlist.

To create a list simply choose one or how many tests you like in test explorer, right click on one of them and choose Add to Playlist; if there is no playlist already loaded, the only option is “New Playlist”, just give the playlist a name and a location and create a new one.

image

Figure 1: Create a playlist from a test in Test Explorer

Now you can continue to add other test to the playlist if you want; once you are done you can select the playlist from the top menu of the Test Explorer.

image

Figure 2: You can now choose the playlist to use.

A playlist is just an XML file that contains the list of all the test you added to the playlist. To continue adding test to the playlist you should use the top Menu to select “All Tests”, find tests you want to add to the playlist, and simple right click and choose to “Add to Playlist”; now you should see all the testlist of the project and not only the “new Playlist” option.

Once you select a playlist, the test runner works exactly as before, but it consider only the tests included in current playlist, you can filter, group by traits, etc etc. To remove a test from a playlist, simply choose that playlist, right click on the test (or the tests) you want to remove and choose: Remove from current playlist.

As I told at the beginning of the post: the use of playlist is an alternative to use Traits to group test and run only a subset, but the main difference is that a Trait expresses a real property of the test, (ex the logical area of the software that got tested, or other attribute such Database to indicate that it needs a test database), while playlist are primarily meant to group together heterogeneous tests to simplify management, both for running test and manage them.

image

Figure 3: Group by traits.

This feature is also needed by all old MsTest users, that are used to create list of test to run with the old test runner.

Gian Maria.

Wpf Design Time Data part 3

If you followed the suggestion of my first couple of posts you should have a dedicated Design Time view model for each real View Model in your application so you can effectively use Design Time Data. You should be aware that Design Time data can be directly manipulated by the designer. In property windows you can see all properties of the Windows object (remember to select the windows), so you can locate the DataContext property and expand it to view its content.

image

Figure 1: Visual Studio designer is able to edit the values of properties of DesignTimeData View Model

Since the designer knows the type of the DataContext it permits you to edit design time value properties directly in Visual Studio. Suppose you want to verify how the UI look when the MainFilter property is a real long string, you can simply change the MainFilter design time data value, inserting a real long string.

image

Figure 2: You can edit properties of Design Time View Model

The designer will immediately reflect the change so you are immediately able to see how the layout of your form is affected from this real long string. If you think this is cool, I can tell you that the VS designer is also able to create complex objects so you do not need to write C# code in constructor of Design Time Data View Model to populate property if you do not want to.

Pressing the button with ellipsis on the Logs property makes you to edit the Logs property directly in the editor, thanks to the build in Collection Editor. This is really cool because you can now decide how much object you want in the collection at design time, but, Houston we have a problem, you can modify properties, but you are not able to create complex objects.

image 

Figure 3: You are not able to fully construct a LogMessageViewModel with the designer

The problem shown in Figure 3 derive from this fact: WPF designer has lots of default designers that permits you to edit standard properties of objects, but if a property if a complex object, like property called Log in Figure 3, it does not know witch editor to use.

If you think to this limitation a little bit, it seems strange, because after all I’m able to create new LogMessageViewModel objects and edit all the properties with Collection Editor; why I’m not able to create object of LogMessage Type from the editor? After all if the Collection editor is able to create complex object I should be able to populate complex properties in the same way. The solution to this problem is specifying to WPF  the editor you want to use with the attribute TypeConverterAttribute. Since I do not want to clutter my ViewModels with attribute pertinent to designer, the simplest solution is to create a DesignTime subclass for each ViewModel, so I proceed to create the LogMessageViewModelDesignData

[NewItemTypes(typeof(LogMessageViewModelDesignData))]
public class LogMessageViewModelDesignData : LogMessageViewModel
{
    [NewItemTypes(typeof(LogMessage))]
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public new LogMessage Log { get; set; }
}

Thanks to this approach I’m able to hide the original Log property with a property that has the appropriate attributes for the designer. This is the same trick used to solve the BindingCollection problem we saw in the previous post, this time I hide the property just to specify the TypeConverterAttribute, so the designer knows how to edit my object. The NewItemTypes attribute is also used to specify the exact type of object I want to create from the designer. Now I need to change the property Logs in the RawLoggerViewModelDesignData, because now it will be a collection of this specific Design Time object

public new ObservableCollection<LogMessageViewModelDesignData> Logs { get; set; }

If you look at the previous post you already know that I hided the original Logs property because it is of ICollectionViewType, a type that is not usable at design time, and I used an ObservableCollection of LogMessageViewModel, but nothing restrict me to declare that this collection contains different objects respect the real ViewModel, as long as the new class has same properties as the real one. It turns out that I can use my new LogMessageViewModelDesignData class as the type attribute for the ObservableCollection and this improves a lot the experience for users that wants to manipulate Design Time data directly from Visual Studio.

image

Figure 4: You can now edit the Log property directly from the designer.

As you can see from Figure 4 the designer actually render a beautiful “New” button that permits you to create new instance for a Complex property. If you press that button a new instance of LogMessage is created and you can edit directly inside the designer. Actually this is a simple commodity to embed design time data directly inside the windows, here is the code that this will generate

image

Figure 5: The designer is simply generating XAML code to populate the properties of the DataContext with the designData attribute

As you can see, this is the very same approach taken on the first post, creating an instance of the ViewModel and populate its property at design time in XAML, the real difference with this approach is we are actually using dedicated subclasses to manage design time data, to overcome limitation in the original viewmodel (Es. filtered collection pattern). This is really cool because gives you the best of both approach, you can programmatically generate meaningful Design Time Data, but you can always override them to verify how the layout of the View will appear with different data.

If you want to revert to the original design time data you can simply delete corresponding XAML part in the Window code, or you can reset the value from designer

image

Figure 6: Pressing the small black square box near the property permits you to reset design time data.

This technique is really useful to populate design time data directly in code to have meaningful value, but giving to the people that will skin your application the ability to change these value to verify how the interface will look with different data.

This is one of the real advantage of using a full MVVM approach. I always heard comment by people telling that MVVM is useful only for Unit Testing the View Model, but this is actually not true. A good MVVM architecture creates a complete separation from the UI appearance and UI Logic and give to the designer an unique experience thanks to Design Time Data.

Alk.

Shim constructors to isolate “Future Objects”

I’ve already blogged previously about the new Shim Library of Visual Studio 2012

Now it is time to explore another scenario where shim can save your life. Suppose you are working with Hardware, Es. a barcode reader and you have a class in your system wrote in this way.

public class BarcodeReader
{
    public BarcodeReader() { 
        //connect to the hardware, if the hardware is not there 
        //throw an exception
    }

    public String ReadCode() 
    {
        //dialogate with the hardware and get the Barcode
    }
}

This class manage the connection to a physical BarcodeReader in the constructor and if something went wrong throws an exception and expose a ReadCode method that ask the Physical reader to read a Barcode. This class is used with the following pattern throughout all the software.

public class MyLogic
{
    private BarcodeReader reader;

    public MyLogic() {
        reader = new BarcodeReader();
    }

    public String RetrieveIndustrialCode()
    {
        String rawCode = reader.ReadCode();
        return rawCode.Substring(2, 10);
    }
}

MyLogic is a class with some business logic based on the Barcode returned from the call to ReadCode() method, as you can see it simply instantiate an instance of BarcodeReader in the constructor and read the code in the RetrieveIndustrialCode Method used to extract the industrial code from the raw content of the barcode. In this stupid example the algorithm to extract the Industrial Code from the Raw barcode read from the reader is simply reading chars from 2 to 10, but in real scenario we could have complex string parsing code that needs to be tested, but how?? As you can see from the code you can test only when the real hardware is connected to the machine because if a physical reader is not connected the BarcodeReader will throw exception, but the most annoying part is that it is impossible to simulate a read during a Unit Test.

This is another scenario where shims comes to the rescue, just add a fakes assembly (as described in the previous samples) and you can write this test.

[Fact]
public void verify_retrieval_of_industrialCode()
{
    using (ShimsContext.Create())
    {
        ShimBarcodeReader.Constructor = @this =>  new ShimBarcodeReader(@this) {
            ReadCode = () => "IC1234567890BLABLABLA",
        };
        MyLogic sut = new MyLogic();
        var industrialCode = sut.RetrieveIndustrialCode();
        Assert.Equal("1234567890", industrialCode);
    }
}

Whenever you fake an assembly, each Shim that gets created has one or more static property called ConstructorXXX, where the XXX part is used to distinguish from the overloaded version using paramers type. In this example I have a default constructor so my Shim has a static property called Constructor. This specific property permits you to intercept the future creation of that type and even substitute it with a shim. This specific property needs a lambda where the first parameter is the Instance of the object being created followed by all other parameters of the constructor. In my sample test I pass a lambda that based on the instance created, returns a new ShimBarcodeReader configured to return the code “IC1234567890BLABLABLA” from ReadCode() method.

This technique is really powerful because permits you to Shim every future instance that will be created for a specific object and makes possible to inject Shims almost everywhere. When the test run, the MyLogic constructor creates an instance of BarcodeReader, but thanks to the Shim library I’m able to pass a shim where I’ve already set the return value of ReadCode() method.

Thanks to this capability I can write tests until I eventually found a bug, to show how the Shim Constructor changes when constructor has parameters, I’ve changed the BarcodeReader class to make the constructor accepts a Single String parameter and I want to write a test that verify that when the BarcodeReader returns an Empty String the Industrial code returned is also Empty.

[Fact]
public void verify_retrieval_of_industrialCode_too_short()
{
    using (ShimsContext.Create())
    {
        ShimBarcodeReader.ConstructorString = (@this, value) => new ShimBarcodeReader(@this)
        {
            ReadCode = () => "",
        };
        MyLogic sut = new MyLogic("COM2");
        var industrialCode = sut.RetrieveIndustrialCode();
        Assert.Equal("", industrialCode);
    }
}

To shim the creation of a ShimBarcodeReader I now need to use ConstructorString property, since the constructor has now a parameter of type String. Thanks to Visual Studio 2012 and Shim Library you can now easily test untestable legacy code with minimum effort.

Gian Maria.

News in the TFS 2012 RC

I heard many different reactions on the new Team Explorer in Visual Studio 2012, some people really likes it, some other still need to familiarize with it, but most of them complained that they find difficult to associate a Work Item to a check in because the drop down list in VS 11 beta only permits you to specify the id of the work item. The only way in VS2012 to associate a WI to the Chec-in is dragging a Work Item from a Query result to the Related Work Items area of Pending Changes

image

Figure 1: Associate a Work Item to the check-in dragging the work item to the Related Work Item area of the Pending Changes section

This behavior is annoying, because we need to go away from the Pending Changes window, navigate to the Work Item section of the Team Explorer, then issue the query to show results, finally return to Pending Changes and execute Drag&Drop. This is quite clumsy, but it is consistent with the new way to work, because the new Team Explorer is designed to easy find own work, so the standard workflow of a programmer is;: open “my work”, start to work on a Task/Bug/etc clicking on “Add to In Progress”, and when it is time to Check-in you already associated the Work Item because it is In Progress, so you do not need to browse to search for Work Item.

Since lots of developer were already used in associating the Work Item during Check-in and not before in the Visual Studio 2012 RC now you have the ability to query Work Item directly from the Pending Changes area, because you have a Queries button that shows all of your personal queries. Once the query ran, you can drag and drop as usual Work Item to the Related Work Items area.

image

Figure 2: Ability to run personal query directly from the Pending Changes area

You have also a third option, just search work item by full text in the appropriate textbox as visible in Figure 3, you just type search query in the textbox, press enter and the choose “Open as Query”, then you can simply press the “back” button on Team Explorer and you are back to Pending Changes where you can Drag Work items to associate to Check-in

image

Figure 3: Full search in Work Item, then open as Query

This third capability is the best one, because permits you to do a Full Text search inside work item, but you can also create with easy complex queries as represented in Figure3 where I search all task assigned to me with the string t=task A:”@Me”. This is much more flexible if you do not have a personal query ready but you remember part of the text of the Work Item or you want simply choose all WI of a certain type assigned to you.

Happy TFS.

Gian Maria

Visual Studio 2012 and TFS 2012 RC is finally out

Yesterday the Release Candidate of TFS2012 and Visual Studio 2012 were released by the Visual Studio team, you can download directly from Microsoft, and yes, the name is now officially Visual Studio 2012 and TFS 2012 🙂

Visual Studio 2012 RC: http://www.microsoft.com/visualstudio/11/en-us

Team Foundation Server 2012 RC: http://www.microsoft.com/en-us/download/details.aspx?id=29918

If you are interested in the changes from the Beta you can check this MSDN Page, you can find also a lot of information from the Visual Studio ALM Rangers, that released the Readiness RC Wave full of important information. We have a good improvement on the upgrade process as described in This post, that explains the new upgrade procedure and how the wizard can avoid breaking something if you have customized a standard TFS Process.

You have also a brand new Developer Tools Blog at this url: http://blogs.msdn.com/b/developer-tools/

Happy Programming.

Gian Maria