Logo

Maarten Balliauw {blog}

ASP.NET, ASP.NET MVC, Azure, PHP, OpenXML, VSTS, ...

About the author

Maarten Balliauw is an MVP ASP.NET and is currently employed as .NET Software Engineer at RealDolmen. His interests are mainly web applications developed in ASP.NET (C#) or PHP.
More about me More about me
Send mail E-mail me


Microsoft Most Valuable Professional - MVP - ASP.NET

Subscribe to my RSS feed Follow me on Twitter! View Maarten Balliauw's profile on LinkedIn RealDolmen - Rock-solid passion for ICT
I'm a speaker at TechDays Belgium and TechDays Finland

Search

Latest Twitter

    Follow me on Twitter...

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

    © Copyright Maarten Balliauw 2010

    ASP.NET MVC TDD using Visual Studio 2010

    Phil Haack announced yesterday that the tooling support for ASP.NET MVC is available for Visual Studio 2010. Troy Goode already blogged about the designer snippets (which are really really cool, just like other parts of the roadmap for ASP.NET MVC 2.0). I’ll give the new TDD workflow introduced in VS2010 a take.

    kick it on DotNetKicks.com

    Creating a new controller, the TDD way

    First of all, I’ll create a new ASP.NET MVC application in VS2010. After installing the project template (and the designer snippets if you are cool), this is easy in VS2010:

    Step 1

    Proceed and make sure to create a unit test project as well.

    Next, in your unit test project, add a new unit test class and name it DemoControllerTests.cs.

    Step 2Go ahead and start typing the following test:

    Step 3Now when you type CTRL-. (or right click the DemoController unknown class), you can pick “Generate other…”:

    Step 4A new window will appear,  where you can select the project where you want the new DemoController class to be created. Make sure to enter the MvcApplication project here (and not your test project).

    Step 5

    Great, that class has been generated. But how about the constructor accepting List<string>? Press CTRL-. and proceed with the suggested action.

    Step 6

    Continue typing your test and let VS2010 also implement the Index() action method.

    Step 7You can now finish the test code:

    Step 8The cool thing is: we did not have to go out of our DemoControllerTests.cs editor while writing this test class, while VS2010 took care of stubbing my DemoController in the background:Step 9Run your tests and see it fail. That’s the TDD approach: first make it fail, and then implement what’s needed:

    Step 10

    If you run your tests  now, you’ll see the test pass.

    Conclusion

    I like this new TDD approach and ASP.NET MVC! It’s not ReSharper yet, but I think its a fine step that the Visual Studio team has taken.

    kick it on DotNetKicks.com


    Categories: ASP.NET | C# | CodePlex | General | ICT | Internet | MVC | VSTS | VS2010

    Book review: Software Testing with Visual Studio Team System 2008

    Software Testing with Visual Studio Team System 2008 Another book review, this time for Packt’s “Software Testing with Visual Studio Team System 2008”. The book introduces you to the main types of testing available in Visual Studio Team System 2008 for both desktop and web applications, and then walks you through deploying, running, and interpreting the results of tests.

    The book starts with an overview of why you need testing and then lists all available test types in Visual Studio 2008. It also explains the differences between a stand alone Visual Studio 2008 and a Team Foundation Server backed version. Each chapter thereafter covers one of the test types in detail: unit tests, web tests, advanced web tests, load tests, manual tests, …

    Next to these things, more information on how to deploy and run tests on a VSTS build server is provided. And when you work with a VSTS build server, chances are big reporting is enabled. These reports are also covered in detail, showing you how to interpret the data displayed.

    I’ve been working with and giving training on Visual Studio 2008 for quite a while now, including a large part on Visual Studio and testing. To be honest, I think this book really covers all aspects of testing in Visual Studio 2008, making it an ideal reference for any development team working with VSTS. Here's the official product page at Packt.

    kick it on DotNetKicks.com


    Verifying code and testing with Pex

    Pex, Automated White box testing for .NET

    Earlier this week, Katrien posted an update on the list of Belgian TechDays 2009 speakers. This post featured a summary on all sessions, of which one was titled “Pex – Automated White Box Testing for .NET”. Here’s the abstract:

    “Pex is an automated white box testing tool for .NET. Pex systematically tries to cover every reachable branch in a program by monitoring execution traces, and using a constraint solver to produce new test cases with different behavior. Pex can be applied to any existing .NET assembly without any pre-existing test suite. Pex will try to find counterexamples for all assertion statements in the code. Pex can be guided by hand-written parameterized unit tests, which are API usage scenarios with assertions. The result of the analysis is a test suite which can be persisted as unit tests in source code. The generated unit tests integrate with Visual Studio Team Test as well as other test frameworks. By construction, Pex produces small unit test suites with high code and assertion coverage, and reported failures always come with a test case that reproduces the issue. At Microsoft, this technique has proven highly effective in testing even an extremely well-tested component.”

    After reading the second sentence in this abstract, I was thinking: “SWEET! Let’s try!”. So here goes…

    Getting started

    First of all, download the academic release of Pex at http://research.microsoft.com/en-us/projects/Pex/. After installing this, Visual Studio 2008 (or 2010 if you are mr. or mrs. Cool), some context menus should be added. We will explore these later on in this post.

    What we will do next is analyzing a piece of code in a fictive library of string extension methods. The following method is intended to mimic VB6’s Left method.

    /// <summary>
    /// Return leftmost characters from string for a certain length
    /// </summary>
    /// <param name="current">Current string</param>
    /// <param name="length">Length to take</param>
    /// <returns>Leftmost characters from string</returns>
    public static string Left(this string current, int length)
    {
        if (length < 0)
        {
            throw new ArgumentOutOfRangeException("length", "Length should be >= 0");
        }

        return current.Substring(0, length);
    }

    Great coding! I even throw an ArgumentOutOfRangeException if I receive a faulty length parameter.

    Pexify this!

    Analyzing this with Pex can be done in 2 manners: by running Pex Explorations, which will open a new add-in in Visual Studio and show me some results, or by generating a unit test for this method. Since I know this is good code, unit tests are not needed. I’ll pick the first option: right-click the above method and pick “Run Pex Explorations”.

    Run Pex Explorations

    A new add-in window opens in Visual Studio, showing me the output of calling my method with 4 different parameter combinations:

    Pex Exploration Results

    Frustrated, I scream: “WHAT?!? I did write good code! Pex schmex!” According to Pex, I didn’t. And actually, it is right. Pex explored all code execution paths in my Left method, of which two paths are not returning the correct results. For example, calling Substring(0, 2) on an empty string will throw an uncaught ArgumentOutOfRangeException. Luckily, Pex is also there to help.

    When I right-click the first failing exploration, I can choose from some menu options. For example, I could assign this as a task to someone in Team Foundation Server.

    Pex Exploration Options In this case, I’ll just pick “Add precondition”. This will actually show me a window of code which might help avoiding this uncaught exception.

    Preview and Apply updates

    Nice! It actually avoids the uncaught exception and provides the user of my code with a new ArgumentException thrown at the right location and with the right reason. After doing this for both failing explorations, my code looks like this:

    /// <summary>
    /// Return leftmost characters from string for a certain length
    /// </summary>
    /// <param name="current">Current string</param>
    /// <param name="length">Length to take</param>
    /// <returns>Leftmost characters from string</returns>
    public static string Left(this string current, int length)
    {
        // <pex>
        if (current == (string)null)
            throw new ArgumentNullException("current");
        if (length < 0 || current.Length < length)
            throw new ArgumentException("length < 0 || current.Length < length");
        // </pex>

        return current.Substring(0, length);
    }

    Great! This should work for any input now, returning a clear exception message when someone does provide faulty parameters.

    Note that I could also run these explorations as a unit test. If someone introduces a new error, Pex will let me know.

    More information

    More information on Pex can be found on http://research.microsoft.com/en-us/projects/Pex/.

    kick it on DotNetKicks.com


    Categories: C# | Debugging | General | ICT | Internet | Pex | Quality code | Testing | TFS | VSTS

    Integrating NUnit test results in Team Build 2008

    When using Team Foundation Server 2008 and Team Build, chances are you are developing unit tests in Microsoft’s test framework which is integrated with Visual Studio 2008. This integration offers valuable data hen a build has been finished on the build server: test run results are published in the Team Foundation Server 2008 data warehouse and can be used to create detailed metrics on how your development team is performing and what the quality of the product being developed is.

    Not all software development teams are using Microsoft’s test framework. Perhaps your team is using Team Foundation Server 2008 and creates (unit) tests using NUnit. By default, NUnit tests are not executed by the Team Build server nor are they published in the Team Foundation Server 2008 data warehouse. The following guide enables you to leverage the features Team Foundation Server 2008 has to offer regarding metrics, by customizing the build process with the necessary steps to publish test results.

    (cross-posted on RealDolmen ALM Blog)

    1. Prerequisites

    Make sure the following prerequisites are present on your Team Build server (in addition to a default build server installation):

    2. Registering NUnit framework in the global assembly cache (GAC)

    For NUnit tests to be run in a Team Build script, make sure that the NUnit framework is registered in the global assembly cache (GAC). This can be achieved by copying the file C:\Program Files\NUnit 2.4.8\bin\nunit.framework.dll to C:\Windows\Assembly.

    clip_image002

    3. Customizing a build script

    After installing all prerequisites, make sure you know all paths where these tools are installed before continuing.

    The build script for a NUnit enabled build should be modified in several locations. First of all, the MSBuild Community Tasks target file should be referenced. Next, a new build step is added in the AfterCompile hook of the build script. This build step will run the NUnit tests in the compiled DLL’s, transform them to a Microsoft Test results file (*.trx) and publish this transformed file to the Team Foundation Server 2008.

    Open the TFSBuild.proj file from source control and merge the following lines in:

    <?xml version="1.0" encoding="utf-8"?>
    <Project DefaultTargets="DesktopBuild" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> 
        <!-- Do not edit this --> 
        <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets" /> 
        <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.targets" /> 
        <ProjectExtensions> 
            <!-- ... --> 
        </ProjectExtensions> 

        <!-- At the end of file: --> 

        <ItemGroup> 
            <AdditionalReferencePath Include="$(ProgramFiles)\Nunit 2.4.7\bin\" /> 
        </ItemGroup> 

        <Target Name="AfterCompile"> 
            <!-- Create a Custom Build Step --> 
            <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Name="NUnitTestStep" Message="Running NUnit Tests"> 
                <Output TaskParameter="Id" PropertyName="NUnitStepId" /> 
            </BuildStep> 

            <!-- Get Assemblies to test --> 
            <ItemGroup> 
                <TestAssemblies Include="$(OutDir)\**\Calculator.dll"/> 
            </ItemGroup> 

            <!-- Run NUnit and check the result --> 
            <NUnit ContinueOnError="true" Assemblies="@(TestAssemblies)" OutputXmlFile="$(OutDir)nunit_results.xml" ToolPath="$(ProgramFiles)\Nunit 2.4.8\bin\"> 
                <Output TaskParameter="ExitCode" PropertyName="NUnitResult" /> 
            </NUnit> 
            <BuildStep Condition="'$(NUnitResult)'=='0'" TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(NUnitStepId)" Status="Succeeded" /> 
            <BuildStep Condition="'$(NUnitResult)'!='0'" TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(NUnitStepId)" Status="Failed" /> 

            <!-- Regardless of NUnit success/failure merge results into the build --> 
            <Exec Command="&quot;$(ProgramFiles)\nxslt-2.3-bin\nxslt2.exe&quot; &quot;$(OutDir)nunit_results.xml&quot; &quot;$(ProgramFiles)\MSBuild\NUnit\nunit transform.xslt&quot; -o &quot;$(OutDir)nunit_results.trx&quot;"/> 
            <Exec Command="&quot;$(ProgramFiles)\Microsoft Visual Studio 9.0\Common7\IDE\mstest.exe&quot; /publish:$(TeamFoundationServerUrl) /publishbuild:&quot;$(BuildNumber)&quot; /publishresultsfile:&quot;$(OutDir)nunit_results.trx&quot; /teamproject:&quot;$(TeamProject)&quot; /platform:&quot;%(ConfigurationToBuild.PlatformToBuild)&quot; /flavor:&quot;%(ConfigurationToBuild.FlavorToBuild)&quot;" IgnoreExitCode="true" /> 

            <!-- If NUnit failed it's time to error out --> 
            <Error Condition="'$(NUnitResult)'!='0'" Text="Unit Tests Failed" /> 
        </Target>
    </Project>

    4. Viewing test results

    When a build containing NUnit tests has succeeded, results of this tests are present in the build log:

    clip_image004

    When clicking the test results hyperlink, Visual Studio retrieves the result file from Team Foundation Server 2008 and displays it in the test results panel:

    clip_image006

    kick it on DotNetKicks.com


    Categories: C# | General | ICT | Internet | Testing | TFS | VSTS | NUnit

    The devil is in the details (Visual Studio Team System test policy)

    Have you ever been in a difficult situation where a software product is overall very good, but a small detail is going wrong? At least I've been, for the past week...

    Team System allows check-in policies to be enforced prior to checking in your code. One of these policies is the unit testing policy, which allows you to enforce a specific test list to be run prior to checking in your code.

    How it is...

    Now here's the catch: what if you have a Team Project with 2 solutions in it? How can I enforce the check-in policy to run tests from solution A only when something in solution A is checked in, tests from solution B with solution B changes, ...

    How it should be...

    Creating a custom check-in policy

    To be honest, there actually are quite enough examples on creating a custom check-in policy and how to install them. So I'll keep it short: here's the source code of my solution (VS2008 only).

    kick it on DotNetKicks.com


    Categories: C# | General | ICT | Projects | Quality code | Testing | TFS | VSTS

    Detailed code metrics with NDepend

    A while ago, I blogged about code performance analysis in Visual Studio 2008. Using profiling and hot path tracking, I measured code performance and was able to react to that. Last week, Patrick Smacchia contacted me asking if I wanted to test his project NDepend. He promised me NDepend would provide more insight in my applications. Let's test that!

    After downloading, extracting and starting NDepend, an almost familiar interface shows up. Unfortunately, the interface that shows up after analyzing a set of assemblies is a little bit overwhelming... Note that this overwhelming feeling fades away after 15 minutes: the interface shows the information you want in a very efficient way! Here's the analysis of a personal "wine tracking" application I wrote 2 years ago.

    Am I independent?

    Let's start with the obvious... One of the graphs NDepend generates, is a dependency map. This diagram shows all dependencies of my "WijnDatabase" project.

    Dependencies mapped

    One thing I can see from this, is that there probably is an assembly too much! WijnDatabase.Classes could be a candidate for merging into WijnDatabase, the GUI project. These dependencies are also shown in the dependency window.

    Dependencies mapped

    You can see (in the upper right corner) that 38 methods of the WijnDatabase assembly are using 5 members of WijnDatabase.Classes. Left-click this cell, and have more details on this! A diagram of boxes clearly shows my methods in a specific form calling into WijnDatabase.Classes.

    More detail on dependencies

    In my opinion, these kinds of views are really useful to see dependencies in a project without reading code! The fun part is that you can widen this view and have a full dependency overview of all members of all assemblies in the project. Cool! This makes it possible to check if I should be refactoring into something more abstract (or less abstract). Which is also analysed in the next diagram:

    Is my application in the zone of pain?

    What you can see here is the following:

    • The zone of pain contains assemblies which are not very extensible (no interfaces, no abstract classes, nor virtual methods, stuff like that). Also, these assemblies tend to have lots of dependent assemblies.
    • The zone of uselessness is occupied by very abstract assemblies which have almost no dependent assemblies.

    Most of my assemblies don't seem to be very abstract, dependencies are OK (the domain objects are widely used so more in the zone of pain). Conclusion: I should be doing some refactoring to make assemblies more abstract (or replacable, if you prefer it that way).

    CQL - Code Query Language

    Next to all these graphs and diagrams, there's another powerful utility: CQL, or Code Query Language. It's sort of a "SQL to code" thing. Let's find out some things about my application...

     

    Methods poorly commented

    It's always fun to check if there are enough comments in your code. Some developers tend to comment more than writing code, others don't write any comments at all. Here's a (standard) CQL query:

    // <Name>Methods poorly commented</Name>
    WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE PercentageComment < 20 AND NbLinesOfCode > 10  ORDER BY PercentageComment ASC
    // METHODS WHERE %Comment < 20 and that have at least 10 lines of code should be more commented.
    // See the definition of the PercentageComment metric here http://www.ndepend.com/Metrics.aspx#PercentageComment

    This query searches the top 10 methods containing more than 10 lines of code where the percentage of comments is less than 20%.

    CQL result 

    Good news! I did quite good at commenting! The result of this query shows only Visual Studio generated code (the InitializeComponent() sort of methods), and some other, smaller methods I wrote myself. Less than 20% of comments in a method consisting of only 11 lines of code (btnVoegItemToe_Click in the image) is not bad!

    Quick summary of methods to refactor

    Another cool CQL query is the "quick summary of methods to refactor". Only one method shows up, but I should probably refactor it. Quiz: why?

    CQL result

    Answer: there are 395 IL instructions in this method (and if I drill down, 57 lines of code). I said "probably", because it might be OK after all. But if I drill down, I'm seeing some more information that is probably worrying: cyclomatic complexity is high, there are many variables used, ... Refactoring is indeed the answer for this method!

    Methods that use boxing/unboxing

    Are you familiar with the concept of boxing/unboxing? If not, check this article. One of the CQL queries in NDepend is actually finding all methods using boxing and unboxing. Seems like my data access layer is boxing a lot! Perhaps some refactoring could be needed in here too.

    CQL result

    Conclusion

    Over the past hour, I've been analysing only a small tip of information from my project. But there's LOTS more information gathered by NDepend! Too much information, you think? Not sure if a specific metric should be fitted on your application? There's good documentation on all metrics as well as short, to-the-point video demos.

    In my opinion, each development team should be gathering some metrics from NDepend with every build and do a more detailed analysis once in a while. This detailed analysis will give you a greater insight on how your assemblies are linked together and offer a great review of how you can improve your software design. Now grab that trial copy!

    kick it on DotNetKicks.com


    New Team Foundation Server projects on CodePlex!

    Busy times... Lots of work, some holidays here in Belgium, ... But there's always time to browse CodePlex! It is actually a good thing to do that from time to time. In the past few days, I spotted two great new projects on Team Foundation Server. Thumbs up for their authors!

    TeamReview

    "Use this Visual Studio Add-In to leverage Team System and the Visual Studio code object model for in-IDE code review feedback, demonstration, and review replay. The inspiration for this project are the many code reviews we've experienced that have been generally underwhelming experiences and less than optimal outcomes. To make code review less painful, and to greatly assist in distributed environment code reviews this project will add Code Review squarely into the VS.Net Team System tools."

    TeamReview is, in my opinion, a great step forward regarding code reviews using Visual Studio and TFS. It consists of a new work item type (for code reviews) and a Visual Studio add-in. The presented workflow is quite easy: a developer creates a code review task for the code reviewer, he answers it with eventual comments. A complete example of this flow, including screenshots, can be found on CodePlex.

    TeamReview Code Review Response

    TFS Sticky Buddy

    Want to know by one look what's going on in your project? Pick a work item query in TFS Sticky Buddy and immediately see what work items are on schedule and which ones are overdue. Since a screenshot might say more than words, here are 2. The left one has multiple iterations, the right one is a project on my demo VPC. Seems like I have a lot of work to do :-)

    TFS Sticky Buddy TFS Sticky Buddy - A lot of work!

    kick it on DotNetKicks.com


    Categories: C# | CodePlex | General | ICT | Projects | Software | TFS | VSTS

    Heroes happen here - Microsoft TechDays 2008 in Belgium

    Microsoft TechDays 2008

    Dolmen polo Just to inform you: together with a numer of colleagues from Dolmen, I'll be attending the Microsoft TechDays 2008 in Ghent, Belgium on 12 and 13 March 2008. Want to spot me, Joris, Jeroen, Danny, ... and meet in person? Search for one of the guys in a Dolmen shirt!

    Update 17/03/2008: Jeroen posted an overview of the inspiring sessions on his blog. 


    Data Driven Testing in Visual Studio 2008 - Part 2

    This is the second post in my series on Data Driven Testing in Visual Studio 2008. The first post focusses on Data Driven Testing in regular Unit Tests. This part will focus on the same in web testing.

    Web Testing

    I assume you have read my previous post and saw the cool user interface I created. Let's first add some code to that, focussing on the TextBox_TextChanged event handler that is linked to TextBox1 and TextBox2.

    public partial class _Default : System.Web.UI.Page
    {
        // ... other code ...

        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(TextBox1.Text.Trim()) && !string.IsNullOrEmpty(TextBox2.Text.Trim()))
            {
                int a;
                int b;
                int.TryParse(TextBox1.Text.Trim(), out a);
                int.TryParse(TextBox2.Text.Trim(), out b);

                Calculator calc = new Calculator();
                TextBox3.Text = calc.Add(a, b).ToString();
            }
            else
            {
                TextBox3.Text = "";
            }
        }
    }

    It is now easy to run this in a browser and play with it. You'll notice 1 + 1 equals 2, otherwise you copy-pasted the wrong code. You can now create a web test for this. Right-click the test project, "Add", "Web Test...". If everything works well your browser is now started with a giant toolbar named "Web Test Recorder" on the left. This toolbar will record a macro of what you are doing, so let's simply navigate to the web application we created, enter some numbers and whatch the calculation engine do the rest:

    Web Test Recorder

    You'll notice an entry on the left for each request that is being fired. When the result is shown, click "Stop" and let Visual Studio determine what happened behind the curtains of your browser. An overview of this test recording session should now be available in Visual Studio.

    Data Driven Web testing

    There's our web test! But it's not data driven yet... First thing to do is linking the database we created in part 1 by clicking the "Add datasource  Add Datasource" button. Finish the wizard by selecting the database and the correct table. Afterwards, you can pick one of the Form Post Parameters and assign the value from our newly added datasource. Do this for each step in our test: the first step should fill TextBox1, the second should fill TextBox1 and TextBox2.

    Bind Form Post Parameters

    In the last recorded step of our web test, add a validation rule. We want to check whether our sum is calculated correct and is shown in TextBox3. Pick the following options in the "Add Validation Rule" screen. For the "Expected Value" property, enter the variable name which comes from our data source: {{DataSource1.CalculatorTestAdd.expected}}

    image

    If you now run the test, you should see success all over the place! But there's one last step to do though... Visual Studio 2008 will only run this test for the first data row, not for all other rows! To overcome this poblem, select "Run Test (Pause Before Starting" instead of just "Run Test". You'll notice the following hyperlink in the IDE interface:

    Edit Run Settings

    Click "Edit run Settings" and pick "One run per data source row". There you go! Multiple test runs are now validated ans should result in an almost green-bulleted screen:

    image

    kick it on DotNetKicks.com


    Categories: ASP.NET | C# | Debugging | General | ICT | Testing | TFS | VSTS

    Data Driven Testing in Visual Studio 2008 - Part 1

    Last week, I blogged about code performance analysis in Visual Studio 2008. Since that topic provoked lots of comments (thank you Bart for associating "hotpaths" with "hotpants"), thought about doing another post on code quality in .NET.

    This post will be the first of two on Data Driven Testing. This part will focus on Data Driven Testing in regular Unit Tests. The second part will focus on the same in web testing.

    Data Driven Testing?

    We all know unit testing. These small tests are always based on some values, which are passed throug a routine you want to test and then validated with a known result. But what if you want to run that same test for a couple of times, wih different data and different expected values each time?

    Data Driven Testing comes in handy. Visual Studio 2008 offers the possibility to use a database with parameter values and expected values as the data source for a unit test. That way, you can run a unit test, for example, for all customers in a database and make sure each customer passes the unit test.

    Sounds nice! Show me how!

    You are here for the magic, I know. That's why I invented this nifty web application which looks like this:

    Example application

    This is a simple "Calculator" which provides a user interface that accepts 2 values, then passes these to a Calculator business object that calculates the sum of these two values. Here's the Calculator object:

    /// <summary>
    ///A test for Add
    ///</summary>
    [TestMethod()]
    public void AddTest()
    {
        Calculator target = new Calculator(); // TODO: Initialize to an appropriate value
        int a = 0; // TODO: Initialize to an appropriate value
        int b = 0; // TODO: Initialize to an appropriate value
        int expected = 0; // TODO: Initialize to an appropriate value
        int actual;
        actual = target.Add(a, b);
        Assert.AreEqual(expected, actual);
        Assert.Inconclusive("Verify the correctness of this test method.");
    }

    As you see, in a normal situation we would now fix these TODO items and have a unit test ready in no time. For this data driven test, let's first add a database to our project. Create column a, b and expected. These do not have to represent names in the unit test, but it's always more clear. Also, add some data.

    Data to test

    Test View Great, but how will our unit test use these values while running? Simply click the test to be bound to data, add the data source and table name properties. Next, read your data from the TestContext.DataRow property. The unit test will now look like this:

    /// <summary>
    ///A test for Add
    ///</summary>
    [DataSource("System.Data.SqlServerCe.3.5", "data source=|DataDirectory|\\Database1.sdf", "CalculatorTestAdd", DataAccessMethod.Sequential), DeploymentItem("TestProject1\\Database1.sdf"), TestMethod()]
    public void AddTest()
    {
        Calculator target = new Calculator();
        int a = (int)TestContext.DataRow["a"];
        int b = (int)TestContext.DataRow["b"];
        int expected = (int)TestContext.DataRow["expected"];
        int actual;
        actual = target.Add(a, b);
        Assert.AreEqual(expected, actual);
    }

    Now run this newly created test. After the test run, you will see that the test is run a couple of times, one time for each data row in he database. You can also drill down further and check which values failed and which were succesful. If you do not want Visual Studio to use each data row sequential, you can also use the random accessor and really create a random data driven test.

    Test results

    Tomorrow, I'll try to do this with a web test and test our web interface. Stay tuned!

    kick it on DotNetKicks.com


    Categories: ASP.NET | C# | Debugging | General | ICT | Testing | TFS | VSTS