Decaying Code

Where code comes to die

About the author

Maxime Rouiller is a passionate .NET technology specialist, working for 7 years in large software development, advocating Agile and TDD. Aware of the latest technological trends, he intervenes as a specialist in the .NET Montréal usergroup and acts regularly as a speaker for Web Form programmers on the MVC platform.

View Maxime Rouiller's profile on LinkedIn

Month List

Is your debugger making you stupid?

What is one of the greatest advance of Visual Studio since the coming of .NET? You might think it is the Garbage Collector or the IL which allows interoperability between languages? I think of one the great advance of Visual Studio 2003 (all the way through Visual Studio 2010) is the debugger. Previously, debugger were hardly as powerful as Visual Studio. And that is the problem.

What is debugger?

The quote from Wikipedia is "a debugger is a computer program that is used to test and debug other programs". The debugger is used to find bugs and figure out how to fix them.

The debugger is used to go step by step, step backward, step-into, etc. All this, in the hope of reproducing a bug.

Why does it make me stupid?

It might be one of the most powerful tools that you have under your hand. But it's also one of the most dangerous. It encourages you to test your software yourself without having tools do the job for you. Once you are done debugging a module, you will never debug it again unless there is a bug in it. Then you start building around this module and you test the new modules against the first module. And then starts the fun. You start modifying the first module but don't test again the first scenario that you built. Now, the next time another developer build something based on the same module, there is two thing that can happen. The first is that the developer is going to be afraid to change the module and will duplicate the code in another module to make sure he doesn't break anything. The second option is that the developer is  going to change the module anyway and rerun the application to make sure he didn't break anything obvious. Okay, there is a third option that consist in adding test to address the new behaviour but we're not interested in the good stuff. Just the bad.

Ripples of the Debugger

Okay. After I just told you this nice little story, what do you think will happen in the future? As the other developers goes into the code, they will add over the modules again and again. As the modifications keep on coming, the module will keep on changing. As the changes goes "debugger tested" only, bugs will start to appear in modules that never had bugs before. To "test" the right behaviour, the team will start to add test script to execute manually to make sure no bugs are left behind. This will require interns or QA people to run the test.

The solution?

Infect your code with test and stop using the debugger. That's simple. I know that Ruby doesn't have a debugger integrated inside the main UI it's using. Ruby developer still manage to deliver quality code without the integrated debugger. In fact, lots of developer manage to make great software without debugger. Running without debugger and test however is NOT the solution. You must ensure that your code is covered with code as much as possible. When you find a bug, make a test that reproduce the bug and fix the production code. As your code gets tested, additional modules will not make break unless they break a test. This is the solution. This is the way to make good and clean code.


Permalink | Comments (3) | Post RSSRSS comment feed

Find and Reproduce Heisenbugs - CHESS is the tool for you

Microsoft is mainly known for 2 things. Windows and Office. However, for programmers,  Microsoft is also know for many more projects/product like .NET, Enterprise Library, ASP.NET MVC, Team Foundation Server, SharePoint, etc.

Among the few tools that are not really known and publicised at the moment are the projects inside Microsoft Research. This is the land of Beta or "software-never-to-be-released". Either the project is too crazy(read: inovative?) or not useful for people at the time. But there is time where a tool stands out and need to be  talked about.

My friend Eric De Carufel recently talked to me about this tool called CHESS from Microsoft Research. He tested it and it allows for testing for those rare bugs that are only found when there is enough concurrency. Those bugs were tested before with stress test. Stress test are not supposed to be used for finding concurrency bugs but they are traditionally used for that too because when a system is under stress, concurrency happens.

CHESS is there to solve this problem. It includes itself among your unit test and try every possible permutation of code that happens asynchronously. This include race condition, dead lock, and what else exists (not an expert in multi-threaded applications).

Of course, I expect Eric to blog more about this amazing software that is coming from Microsoft's Trenches.

Want more information? Get on the CHESS website. If you want to find more interesting projects that Microsoft's genius are working on, visit Microsoft Research.


Categories: c# | research | software | unit test
Permalink | Comments (0) | Post RSSRSS comment feed

CodeCamp Montreal 2009 - Unit testing with Moq

I'm happy to announce you that I've been selected to present a session at the Montreal CodeCamp.

My session is going to be focussed on Moq and unit testing. Since simply looking at a framework can be done simply, I'll be going over the framework and many "how-to". I'll also try to fit a few interesting demo with some "refactoring for unit test". Of course, this will all be centered around "best practices" since it's the theme of this year.

See you all there!


Categories: mock | moq | presentation | unit test
Permalink | Comments (0) | Post RSSRSS comment feed

5 reasons why you should use ASP.NET MVC

I'll be fair with you readers. I've only toyed with the ASP.NET MVC framework. It looks great as of now but it's the first full blown MVC framework that we have that is backed by Microsoft. However, there is a lot of opposition nowadays that tend to be formulated like this:

Why should I use ASP.NET MVC? WebForms works well.

Other problems come from the lack of server controls. When a developer look at that and he then wonder why he should have to write HTML and Javascript when before he could have retrieved all that beautiful information with a simple postback.

So without ranting any further, here is 5 reasons why you should use ASP.NET MVC.

1. Testability

When the MVC model is properly applied, it allow for a better separation of your business logic and your presentation code. If the view is not included inside your model, you can easily test without requiring a web server. By default, when starting a new MVC project, Visual Studio offer to create a new Unit Test project based on Microsoft's Unit Test framework. Other Unit tests framework can also be configured to be used by default instead of Microsoft's solution.

The way the code is also made, the controller is the one handling the calls from the route. They can be instantiated outside of a web request which makes them easy to test too.

2. Perfect control of the URLs

ASP.NET MVC use URL Routing to better control the request and forward them to your controllers. Instead of 1 to 1 mapping, they allow pattern matching. The default being "{controller}/{action}/{id}" with the default being "Home/Index". This technically allow you to set the URLs exactly how you want. You don't have to create folder for every level deep it goes. The URL routing allows you to make clean URL that will be easy to remember.

Would you rather try to remember http://localhost/Sales/DisplayProduct.aspx?ProductID=23213 or http://localhost/Product/Detail/23213 ? Even better, if you are an e-Commerce site and want some fast link.... you can directly bind those URL to http://localhost/23213 to make it more easy to remember. Doing that in WebForm while keeping all this unit testable would just be too time consuming now is it?

3. Better Mobility Support

In WebForm, you would have to detect on each page that the browser is a mobile and adapt your rendering for the mobile on each and every form. You could also redirect the user to different page when it's a mobile. What is excellent with MVC is that it's not the view that is receiving the request. It's the controller. The controller can then dynamically decide which view to render while keeping the same URL. So to see a product view, you don't even need to send different URL to different provider. You just detect which device you are handling and redirect it to the proper view. As you support more and more mobile device, you can keep on adding view that are more specific to each device. Want to support this new HTC? Create a view, detect the browser and ensure the right view is displayed. Want to support some iPhone goodness with some device specific HTML? Create the necessary view, reuse the browser detection and display the view.

You can keep on doing that ad infinitum and as much as you want depending on your audience. Having Mobile support now is more convenient than it has ever been.

4. View Engines

Now if you only built ASP.NET WebForms, this term might be weird for you. Let's just say that you have been using the same view engine all this time without wondering if you could choose. The WebForm view engine is... well... what you have been using all this time. This includes server tags (<% %>), binding tags (<%# %>) as well as control tag (<asp:TextBox ... />).

The Spark Engine is a good example. MvcContrib also offer 4 different view engine (Brail, NHaml, NVelocity, XSLT). Each of those engine are created to fix some specific problems. Different view engines can be used on different view. One page could be handled with WebForm view engine, one with Spark Engine, one with XSLT, etc. Different view, different problem different solution.

You might not have to use those, but the simple fact that they are available will make your life easier if they are needed.

5. Built-in and shipped jQuery support

Let's keep the best for the end. jQuery is shipped with any new project instance of ASP.NET MVC. Since Microsoft announced support for jQuery, it's been the big buzz in the javascript world. Since ASP.NET MVC don't rely on Postback, a strong javascript framework is needed to provide for all the UI the previous server control were offering. jQuery easily offer you AJAX, DOM manipulation, event binding and  this across browser.

Of course, jQuery is not an advance to MVC itself. But it is a serious offering from ASP.NET MVC. No more download or "I'll write my own" stuff. I don't know for all of you but if I have to do javascript, I normally do a document.getElementById. This will work in most browsers but as soon as you start going funky, some browser will misbehave. jQuery simply allow you to write $("#myControlId") or many more shortcuts to simply do what you need across browsers. Just by having jQuery available stops me from writing incompatible code.

Conclusions

Lots of point goes toward MVC. Way more could be added. You certainly don't want to miss Kazi Manzur Rashid's blog about ASP.NET MVC Best Practices (part 1, part 2). Scott Hanselman, Phil Haack also have great posts about ASP.NET MVC.

Don't be fooled. Web Forms are not necessarly evil. They just aren't leading you to a pit of success.


Categories: architecture | asp.net | c# | mvc | unit test
Permalink | Comments (11) | Post RSSRSS comment feed

TDD: How I applied TDD to a simple problem

A month or two ago I had to built a component that had to analyse a string a return some information out of it. The best result for this was a Regular Expression and I was sure. So I started writing what kind of input would be valid and which one should not be allowed.

When I started writing this code, I already read many blog posts about it and wanted to give it a try. Since I wanted a simple scenario which would easily be applied, when I had to parse this string I knew I had a simple problem to which I could apply it.

If anyone has ever worked with regular expressions, it is widely known that it's easy to make something match. However, it's really hard to make it match what you want and not what you don't want. For proof of that, try seeing how many regular expression there is to parse a phone number. The non-matches is as important as the matches.

So I started a test project and added my first test. The test was to test the perfect scenario. Of course the test didn't even compiled. I then proceeded to create the missing classes and made the test compile. Of course, all the class had the following inside them:

throw new NotImplementedException();

This ensured that the test "went red". I then proceeded to implement the minimum necessary to make it pass and make it "go green". And I kept on rolling until it worked in all my specified cases. Sometimes, previous tests went and failed. Sometimes, everything stayed green but I kept on going.

For experienced TDD-er it's common and normal. But for me, it was weird. I made sure to follow EXACTLY what it said. When it said "minimum necessary to make it pass", I made sure that I returned a constant if I could or proceeded to create/modify the regular expression as needed. And as I kept increasing my amount of test, the constant all went away, the regular expression got more precise and every time that I broke a test I came back to fix it. It's a weird feeling but when I gave my class for usage, it was working as perfectly as it could.

So why the ruckus? Because since I wrote this piece of code, I haven't seen one bug report. The code is perfect for what it is doing. When a bug will come my way, I'll try the TDD-er way of doing thing. Add a test that reproduce the bug and fix my code to make sure it works on all test.

Result of everything? One bug ridden class, 20 something tests and one developer who learned the essence of TDD.

I would love to get my teeth on more complex code now.


Permalink | Comments (0) | Post RSSRSS comment feed

Part 3 - Advanced mocking functionalities of Moq

See also: Part 1 - Part 2

When you have some simple scenario like "when the method "GetTax" is called, return 5$" it's a simple scenario that a lot of mockers will see. However, there is some rarer scenario that people will wonder how to do it.

One of those scenario is with event handlers. The scenario would be like "if a Product is added to a ShoppingCart, a ProductAdded event should be fired".

Let's start with the basic class bellow which implement our scenario:

namespace MoqSamples
        {
        public interface IProduct
        {
        bool IsValid { get; }
        }

        public class ProductEventArgs : EventArgs
        {
        public ProductEventArgs(IProduct product)
        {
        Product = product;
        }

        public IProduct Product { get; private set; }
        }

        public class ShoppingCart
        {
        private readonly List<IProduct> Products = new List<IProduct>();
        public event EventHandler<ProductEventArgs> ProductAdded = delegate { };

        public void Add(IProduct product)
        {
        if (product.IsValid)
        {
        Products.Add(product);
        ProductAdded(this, new ProductEventArgs(product));
        }
        }
        }
        }

Event Handlers

What we want to test here, is every time we add a valid product an event ProductAdded should be fired.

I have played with Moq a bit trying to get it to work with ShoppingCart. As I tried to mock the event, I tried to create mocks and use the instructions on Moq site but wasn't able to make it happen. If I tried to mock the class itself it wouldn't allow me to do expectations even if I extracted an interface out of it. If I mock the interface, I lose the logic inside my class. I was thinking about creating a mocked event handlers and see if it ever get called but... you need a mock to create a mocked event handler. With this, we'll have to wait for Moq 3.0 (which is in beta at the moment of writing this article). Here is the test I came up with that didn't work :

[Test]
        public void Adding_A_Valid_Product_Fire_Event()
        {
        // Setup our product so that it always returns true on a IsValid verification
        Mock<IProduct> product = new Mock<IProduct>();
        product.Expect(currentProduct => currentProduct.IsValid).Returns(true);

        // setup an event argument for our event
        ProductEventArgs productEventArgs = new ProductEventArgs(product.Object);

        // setup a mocked shopping cart to create our mocked event handler and a true shopping cart to test
        Mock<ShoppingCart> mockedShoppingCart = new Mock<ShoppingCart>();

        //creating the event a mocked event
        MockedEvent<ProductEventArgs> mockedEvent = mockedShoppingCart.CreateEventHandler<ProductEventArgs>();
        mockedShoppingCart.Object.ProductAdded += mockedEvent;
        mockedShoppingCart.Expect(shopping => shopping.Add(product.Object)).Raises(mockedEvent, productEventArgs).Verifiable();

        //making the test
        IShoppingCart myShoppingCart = mockedShoppingCart.Object;
        myShoppingCart.Add(product.Object);

        mockedShoppingCart.Verify();
        }

And here is my simple fix to test this:

[Test]
        public void Adding_A_Valid_Product_Fire_Event()
        {
        // Setup our product so that it always returns true on a IsValid verification
        Mock<IProduct> product = new Mock<IProduct>();
        product.Expect(currentProduct => currentProduct.IsValid).Returns(true);

        // setup an event argument for our event
        ProductEventArgs productEventArgs = new ProductEventArgs(product.Object);

        // creating our objects and events
        ShoppingCart myShoppingCart = new ShoppingCart();
        bool isCalled = false;
        myShoppingCart.ProductAdded += (sender, e) => isCalled = true;

        // Testing the Add method if it fire the event
        myShoppingCart.Add(product.Object);

        // make sure the event was called
        Assert.AreEqual(isCalled, true);
        }

Way more small and more efficient with the mocking. Sometimes, it's better not to try to bend the framework and find the shortest solution that works.

Moq Factories

Moq have factories to help centralize the mocking configuration. The only two configuration available is CallBase and DefaultValue. Every mock created with the factories will allow you to reuse the configuration and reduce the amount of line for setting up the mock.

Here's a sample for the factory initialization:

[Test]
        public void Moq_Test_With_Factories()
        {
        // Initialize factories with default behaviours
        MockFactory mockFactory = new MockFactory(MockBehavior.Default);

        // Setup parameters for mocking
        mockFactory.CallBase = true;
        mockFactory.DefaultValue = DefaultValue.Mock;

        // create mocks with the factory
        Mock<IProduct> product = mockFactory.Create<IProduct>();
        }

This is of course really easy but... what about the parameters?

CallBase

CallBase is defined as "Invoke base class implementation if no expectation overrides the member. This is called "Partial Mock". It allows to mock certain part of a class without having to mock everything.

DefaultValue

There is 2 possible values here. One of them is "Empty" which return default value of the class. The one used in the example is "Mock" which allows "automocking". If a property is mockable, a mock is automatically returned.

Constructor

The constructor of the MockFactory needs a MockBehaviour parameter. 3 values are possible, Default, Loose and Strict.

Strict mock makes mocked object throw an exception for every call to a mocked object that doesn't have an expectation. Loose (which is also Default) will always return default values or empty arrays or null.

By using the factory properly, it's possible to set one style of mocking and reuse theses settings without having to rewrite 1 or 2 more lines per mock.


Categories: c# | mock | moq | unit test
Permalink | Comments (2) | Post RSSRSS comment feed

Unit testing Internals member of a solution from another project

Here is a little bit of knowledge that lots of people are not aware of. There is an Attribute that is InternalsVisibleToAttribute that allows access to a specific external project (the unit test project).

This attribute, once inserted inside AssemblyInfo.cs, will grant "public" visibility to all internal members of the project to the project specified within the attribute.

Here is how it is shown on MSDN:

[assembly:InternalsVisibleTo("MyAssembly, PublicKey=32ab4ba45e0a69a1")]
        

It is however wrong and will never work. The main reason is that what is there let us believe that it's the PublicKeyToken but it is in fact the PublicKey as clearly typed there.

So... how do we get this PublicKey? By executing the following command:

sn -Tp MyAssembly.dll

The result is going to be something like the following:

Public key is
        0024000004800000940000000602000000240000525341310004000001000100adfedd2329a0f8
        3e057f0b14e47f02ec865e542c2dcca6349177fe3530edd5080276c48c6d02fa0a6f67738cc1a0
        793be3322cf17b8995acc15055c00fa61b67a203c7eb2516922810ff0b17cd2e08492bdcafc4a9
        23e6fff4caba672a4c2d0d0f5cac9aea95c3dce3717bb733d852c387f5f025c42c14ec8d759f7e
        b13689be
Public key token is 96dfc321948ee54c

Here is the end result to make it properly visible:

[assembly: InternalsVisibleTo("AssemblyB, PublicKey="
        + "0024000004800000940000000602000000240000525341310004000001000100adfedd2329a0f8"
        + "3e057f0b14e47f02ec865e542c2dcca6349177fe3530edd5080276c48c6d02fa0a6f67738cc1a0"
        + "793be3322cf17b8995acc15055c00fa61b67a203c7eb2516922810ff0b17cd2e08492bdcafc4a9"
        + "23e6fff4caba672a4c2d0d0f5cac9aea95c3dce3717bb733d852c387f5f025c42c14ec8d759f7e"
        + "b13689be" )]

After this step is done, all reference to internal members are considered "public" for this specific project. This simple trick allows you to complete your tests and don't gives any excuse not to test.


Categories: c# | code snippet | unit test
Permalink | Comments (0) | Post RSSRSS comment feed