As a continuation to my recent rant about the differences between programmers and developers and how programmers love to code and … well, everything it is mentioned in that post, I felt like sharing a little bit of fun I had with this stackoverflow question.

Since it had already been answered and actually there was a little debate going on about the pros and cons of the accepted answer I was about to close it and look for something else when I decided to have a little bit of fun and make the solution generic.

Not like it was difficult, after a couple of minutes I had this:

    public class PropertyValidator
    {
        public bool Validate<T, TResult>(IEnumerable<T> list, Func<T, TResult> expression)
        {
            return list.Select(expression).Distinct().Count() <= 1;
        }
    }

But the fun didn’t end there, since this was not needed in what I was working on I had to demonstrate that it worked by other means, what could those means possibly be? You guessed it, unit tests!

    [TestClass]
    public class SameValueInPropertyValidatorTests
    {
        private PropertyValidator _validator;

        [TestInitialize]
        public void Initialize()
        {
            _validator = new PropertyValidator();
        }

        [TestMethod]
        public void ReturnsTrueIfListIsEmpty()
        {
            var list = new List<string>();
            Func<string, string> expression = x => x;

            var result = _validator.Validate(list, expression);

            Assert.IsTrue(result);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForStrings()
        {
            var list = new List<string> {"1", "1", "1", "1", "1", "1"};
            Func<string, string> expression = x => x;

            var result = _validator.Validate(list, expression);

            Assert.IsTrue(result);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForStrings()
        {
            var list = new List<string> { "1", "1", "2", "1", "1", "1" };
            Func<string, string> expression = x => x;

            var result = _validator.Validate(list, expression);

            Assert.IsFalse(result);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForKeyValuePair()
        {
            var list = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("any1", 1),
                new KeyValuePair<string, int>("any2", 1),
                new KeyValuePair<string, int>("any3", 1),
                new KeyValuePair<string, int>("any4", 1),
            };

            Func<KeyValuePair<string, int>, int> expression = x => x.Value;

            var result = _validator.Validate(list, expression);

            Assert.IsTrue(result);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForKeyValuePair()
        {
            var list = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("any1", 1),
                new KeyValuePair<string, int>("any2", 1),
                new KeyValuePair<string, int>("any3", 456),
                new KeyValuePair<string, int>("any4", 1),
            };

            Func<KeyValuePair<string, int>, int> expression = x => x.Value;

            var result = _validator.Validate(list, expression);

            Assert.IsFalse(result);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForEnumProperty()
        {
            var list = new List<Car>
            {
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
            };

            Func<Car, Colors> expression = x => x.Color;

            var result = _validator.Validate(list, expression);

            Assert.IsTrue(result);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForEnumProperty()
        {
            var list = new List<Car>
            {
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Black},
                new Car {Color = Colors.Red},
            };

            Func<Car, Colors> expression = x => x.Color;

            var result = _validator.Validate(list, expression);

            Assert.IsFalse(result);
        }

    }

And since we were on a roll, why not remove the duplication by creating generic methods to assert the results:

    [TestClass]
    public class SameValueInPropertyValidatorTests
    {
        private PropertyValidator _validator;

        [TestInitialize]
        public void Initialize()
        {
            _validator = new PropertyValidator();
        }

        [TestMethod]
        public void ReturnsTrueIfListIsEmpty()
        {
            var list = new List<string>();
            Func<string, string> expression = x => x;

            AssertIsTrue(list, expression);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForStrings()
        {
            var list = new List<string> { "1", "1", "1", "1", "1", "1" };
            Func<string, string> expression = x => x;

            AssertIsTrue(list, expression);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForStrings()
        {
            var list = new List<string> { "1", "1", "2", "1", "1", "1" };
            Func<string, string> expression = x => x;

            AssertIsFalse(list, expression);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForKeyValuePair()
        {
            var list = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("any1", 1),
                new KeyValuePair<string, int>("any2", 1),
                new KeyValuePair<string, int>("any3", 1),
                new KeyValuePair<string, int>("any4", 1),
            };

            Func<KeyValuePair<string, int>, int> expression = x => x.Value;

            AssertIsTrue(list, expression);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForKeyValuePair()
        {
            var list = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("any1", 1),
                new KeyValuePair<string, int>("any2", 1),
                new KeyValuePair<string, int>("any3", 456),
                new KeyValuePair<string, int>("any4", 1),
            };

            Func<KeyValuePair<string, int>, int> expression = x => x.Value;

            AssertIsFalse(list, expression);
        }

        [TestMethod]
        public void ReturnsTrueWhenValuesAreSameForEnumProperty()
        {
            var list = new List<Car>
            {
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
            };

            Func<Car, Colors> expression = x => x.Color;

            AssertIsTrue(list, expression);
        }

        [TestMethod]
        public void ReturnsFalseWhenValuesAreNotSameForEnumProperty()
        {
            var list = new List<Car>
            {
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Red},
                new Car {Color = Colors.Black},
                new Car {Color = Colors.Red},
            };

            Func<Car, Colors> expression = x => x.Color;

            AssertIsFalse(list, expression);
        }

        private void AssertIsTrue<T, TResult>(IEnumerable<T> list, Func<T, TResult> expression)
        {
            var result = _validator.Validate(list, expression);

            Assert.IsTrue(result);
        }    

        private void AssertIsFalse<T, TResult>(IEnumerable<T> list, Func<T, TResult> expression)
        {
            var result = _validator.Validate(list, expression);

            Assert.IsFalse(result);
        }    
    }

Not exactly a break through discovery or even a coding kata but still it was a cute exercise for me to kill some time.

Would you like to share your favorite exercises or your sources of inspiration for coding research? I’d love to hear about them.

I dare say that the people who are kind enough to read this blog already know that I am a little freakily fanatic about unit testing. Believe it or not I do have a lot of experiences in which having unit tests in the code I was modifying saved me from doing very stupid and embarrassing mistakes and I want to share a very recent, although small, example.

For the past month I have been getting into Single Page Application development, better known as SPA and I find this book to be quite insightful. Anyway, when I read technical books I like to code all the examples and make sure they run as the book claims they do, I find I learn better that way. On the very first one, after coding a very large portion of JavaScript, I fired up the browser and … well nothing happened. I looked at the browser’s console and there were no errors whatsoever. To make a long story short I spent almost an hour reviewing and comparing the code to the book line by line, even with the downloaded code which worked. File comparing tools were not helping at all and it was a quite frustrating hour.

Finally I realized I had a typo in the following line:

var result = modal.$container.height === newConfig.heigt;

It was so subtle! Of course the newConfig object did not have a “heigt” property so its value was undefined, which of course is different that whatever value the height property in the container had and so the result was always false.

Of course I do not pretend that we should be writing unit tests for the code we copy from technical books. My point is that in a real project this kind of errors in a language like JavaScript could not only happen but cause to waste a lot of debugging time. All this time would be better spent writing a unit test that would immediately fail and point you in the right direction so the typo is found quickly and corrected, before it even reaches QA, UAT or, God forbids, production.

Because of what’s going on in the software development industry with things like mobile development and SPAs, JavaScript is gaining a lot of importance so we better start to get used to the idea, not only that we’ll be coding a lot more with this language but that we need to be concerned at unit testing that code too.

Recently I read a blog post that discusses the differences between a programmer and a developer. After reading the first couple of paragraphs my first reaction was to think that I consider myself to be a programmer but, because of all the “inherent characteristics” that programmers must have, according to this definition, this thought was very short lived.

The first characteristic that is discussed about programmers is that they love to write code. Well, this is something that it is very easy to feel identified with. Not very many people who write code for a living do so without loving it, and those who do usually move on to other things in a relatively short while. Personally I love to write code and I am never satisfied with the end result, no matter how much work I put into it, I always have this nagging feeling that there are ways to improve it. I will confess that sometimes after the writing is done I stare at the overall solution and marvel at a piece of code that is elegant, simple to understand, easy to maintain, fully testable and, to a reasonable extent, covered in unit tests. Even though that, I still get the feeling that I could improve the work further but that does not mean I sometimes do come up with code that is still beautiful, even if I say so myself, and these characteristics that have been mentioned are my definition of beautiful code. Up until this moment I still complied with this definition of programmer.

The second characteristic is that a programmer writes code just for the mere pleasure of it, even if that code does not fulfill any particular need other than programmer’s needs. Even this makes perfect sense to me since we, as programmers, by writing code just for the sake of it we keep sharp, enhance our skills, feed our curiosity and encourage the everlasting search of the best way to implement something. How often do you just happen to be writing some random code and realize that what you are implementing, or the way you are implementing it, could be used to improve some code you wrote a while back or that it solves the problem in which you are currently working on? I bet this has happen more than once to you. This overall idea still made sense in making me put myself in the “programmer club”.

The next trait that a programmer has, according to the author, is that she knows how her code works so she does not need to write tests at all since she knows where the code might break and she knows how to avoid it. Wait a second, WHAT?! Are you serious? Are you trying to tell me that this is a trait and something to be proud of? Hell, no! Of course any programmer, or coder for that matter, can write code without tests, just like any manufacturer of any product you can think of can manufacture said product without any kind of quality assurance process and still every single manufacturing plant in the world ensures that their products comply with a minimum quality standard. In my book, anybody who aspires to have the noble title of programmer should go out of her way to make sure her code has a minimum code coverage that ensures that said code does what she intends it to do. Even if it is just an exercise, a kata, research something or an excuse to hang out with the computer and forget about society for a while.

So I kept reading and I got to the part where, as a programmer, the author would rather be in his study coding day and night without talking to anybody and having nobody talking to him and be able not to attend any meetings. So he says that real programmers are like geeky theoretical physicist locked up in university labs and who alienate themselves from all human beings. Wait, I’ve seen this before, oh yeah, right! He thinks programmers should be like Sheldon Cooper from The Big Bang Theory! Jokes aside, there are quite a few things to say about this but that will be on a later post.

Honestly this kind of stereotypical description of what a programmer should be is so 1980′s that I am very concerned that there may be a lot of people out there who still believe it. People who think they are doing Agile but in reality they are still doing waterfall with daily stand up meetings, people who claim to be professional programmers and in reality are just cowboy coders putting a huge amount of spaghetti code together that only they can change, and even then they cause a lot of regression errors in the process which they solve by entangling the spaghetti even more. There even is still people who refuses to learn the necessary techniques to go into these kind of messes and start to improve them even though there is a lot of literature available that discusses which techniques are those and how to apply them like this one and this one.

Seriously if you want to be called a programmer instead of a developer like the author of this blog suggests that is fantastic, but embrace the modern definition of it, learn, acquire, and apply the right set of skills and, most importantly, develop the right attitude required for the job, forget about this old school mombo-jumbo and become a proud professional programmer.

Software development has changed a lot in just a few years. I remember not very long ago that it was common and expected to work long hours, even pull all nighters just to be able to meet a deadline or worse because the deadline was the following day and there were still dozens of defects to be fixed so the deliverable would barely work. Those days, fortunately, seem to be long gone. I have not been in a project where I have had to do those kind of stupid things, of course there have been times that I have worked a little overtime but those have been the exception rather than the rule.

Unfortunately there are a lot of managers who were developers in those days who still think that we live in those days and expect their development teams to work in that fashion. Not only expect it, but demand it.

Quite recently I was assigned to a project for one of the major credit card companies and we were having our planning game for the upcoming iteration. One of the stories was particularly large so we suggested to break it down in more manageable pieces and gave our estimates to which one of the customer’s managers said, and I quote, “I can lock down a couple of guys in a room and they will have this feature ready in a couple of days”. Needless to say every single one of the members in the team was quite upset about this remark. This was not a matter of challenging our estimate but to question our professionalism. Besides, it is widely known these days that this is the worst way of developing software since it is completely counterproductive and error prone, by the twelfth hour both guys would be making careless mistakes which would generate several very hard to debug defects and the readability of the code would be questionable to say the least.

Anyway, putting aside the fact that we were quite offended by his comment, you can probably imagine how this manager visualized how his team of a couple of guys could deliver his feature. In the end there is absolutely no doubt in my mind that these two guys would pull it off, I have seen it many times before, some brilliant hero style developer getting a required feature to work in record time just before the deadline and he saves the day.

Of course as time goes by this feature will have to be maintained, defects will have to be fixed and requirements will change and guess what, the only person capable of doing that maintenance would be the hero developer who wrote the code because it is so tightly coupled and so tangled up that he is the only one who can understand what it is doing. Of course there would be no tests whatsoever so every time the code would get changed there would definitely be regressions all over the place. Every developer in the organization would dread the idea of working on that piece of code. Not to mention the huge expense these maintenance efforts would be.

I find it hard to believe, and really sad, that there are people, managers and developers alike, who think that we can and should develop software in this fashion. It almost seems as if these people have been living under a rock and have not heard anything about the trends of how to increase the quality of a software product. These people truly believe that the effort put on properly engineering the code and covering it with tests is a waste of time.

To be honest, sometimes I feel I am on the losing end of the battle and the vision of seeing software being developed with discipline and sound engineering practices is but a dream. But you know what, I do not care. I will keep pushing for building software with all the quality characteristics that so much literature, both off an online, is talking about. I will keep fighting against the idea that software development is somewhat of an art; that has got to stop. I will keep trying to evangelize as many people as I can and someday, maybe, we will see that software is built the same way as buildings, bridges, cars, or airplanes, with repeatable practices and solid discipline. I know I am not alone, there are lots of people who are striving for this, and we really hope you will be on our side.

A little while ago I mentioned that in his book Microsoft .Net Architecting Applications for the Enterprise, Dino Esposito says that a working untestable software product is no different than a working testable one; I am paraphrasing, but that the second one will have a better design. I also said that I did not agree with the first part of this statement and I promised that I would expose my arguments so, here we are.

First of all I want to make perfectly clear that I have the highest respect for Mr. Esposito. I believe he is brilliant and every developer who uses Microsoft’s technologies should read as much of his work as possible. So with that out of the way, let’s begin.

I believe that a software product is a living organism that after it is born it grows, changes, reacts to external stimuli, it can even reproduce in the form of other software that uses some of its components. Of course it cannot do it by itself, it is us the developers who make that happen and of course, we do not do it because we have nothing better to do, we do it because someone asked for it. The important thing to keep in mind is that whoever requested the work to be done on that software needs it for one of two reasons: to make money or to save money.

Our customers embark themselves on the arduous, painful, and stressful activity of sponsoring a software product because they have a specific business need and they hope that their new or enhanced software will eventually produce an increase in sales or profit, an increase in productivity, an improvement of their processes, or something of the sort which in the end it just drills down to making or saving money.

To illustrate this let’s imagine there are two competing companies that have a software product which provides all kinds of academic support to schools and universities. It turns out there is a new trend among universities which provides an amazing business opportunity to these companies but they need to enhance and add new features to their products in order to support it. Both products have been developed in-house and they still have their original teams working for these companies so all the developers know their respective code inside out. Both products work well and their code bases are reasonably clean.

After just a few months the first company has implemented just enough of the new features in order to provide the new services. They were able to do it quickly because every time a modification was ready their automated tests told them right away which existing features would break so the issues were dealt with immediately and the QA team did minimal regression testing so they could focus on testing deeply the new requirements.

On the other hand, the second company is still struggling with their release. Every time a new feature is checked in, the QA team needs to spend a few days on a full regression testing effort and when they find either something that broke or a defect on the new features the code goes back to the dev team, of course, which spends a few days figuring out how is it that the new feature broke the old one and how they can make both of them coexist.

Eventually the second company releases its product. Unfortunately their competitor’s has been around for some time now and they have been able to keep their existing customers, get new ones and even take a few of their competitor’s ones.

As you can see, in this fairy tale which can very well happen in the real world, both companies had a working software product, I never said that neither of them had a mess in their code quite the opposite, the only difference was that the first one was designed for testability and had a good suite of tests. Their product helped them to increase their sales so its main objective was fulfilled. The second company since they could not get their product to market quickly enough, lost market share, lost sales and the big investment on their software will be recovered later, if at all.

And there you have it, even though the second company had a working software product, in the end, it did not work for their benefit so do yourselves and your employers or customers a huge business favor and be sure to insist on designing the product with testability in mind and having a great suite of tests to protect it.

Just this week I blogged about how to assert the message of an expected exception and one of the things I was mentioning is how quite some people had proposed different implementations.

Today I found this post from a fellow blogger in which he talks about the MSTest Extensions library. Basically it explains how to install the NuGet package and shows a small example of how to use the ExceptionAssert method to fulfill the need of asserting the thrown exception’s message.

Unfortunately this implementation still suffers from the limitations that we discussed the last time, it can only deal with Actions so if you want to test a method with a return value or a constructor, this option will not provide a solution.

Not everything about this option is bad though, the use of generics is a nice touch so I thought I could include a couple of improvements to the solution I proposed:

    public static class AssertException
    {
        public static void Is<T>(string message, Delegate action, params object[] parameters) where T : Exception
        {
            try
            {
                action.DynamicInvoke(parameters);
                Assert.Fail(string.Format("Expected exception of type <{0}> with message <{1}> but none was thrown.", typeof(T).Name, message));
            }
            catch (Exception ex)
            {
                if (ex is AssertFailedException || ex is AssertInconclusiveException) throw;

                if (ex.InnerException == null)
                {
                    Assert.IsTrue(ex is T, string.Format("Expected exception type: <{0}> Actual: {1}", typeof(T).Name, ex.GetType().Name));
                    Assert.AreEqual(message, ex.Message, true, CultureInfo.InvariantCulture);
                }
                else
                {
                    Assert.IsTrue(ex.InnerException is T, string.Format("Expected exception type: <{0}> Actual: {1}", typeof(T).Name, ex.InnerException.GetType().Name));
                    Assert.AreEqual(message, ex.InnerException.Message, true, CultureInfo.InvariantCulture);
                }
            }
        }

        public static void Is(Exception expected, Delegate action, params object[] parameters)
        {
            try
            {
                action.DynamicInvoke(parameters);
                Assert.Fail(string.Format("Expected exception of type <{0}> with message <{1}> but none was thrown.", expected.GetType().FullName, expected.Message));
            }
            catch (Exception ex)
            {
                if (ex is AssertFailedException || ex is AssertInconclusiveException) throw;

                if (ex.InnerException == null)
                {
                    Assert.IsTrue(expected.GetType().IsInstanceOfType(ex), string.Format("Expected exception type: <{0}> Actual: {1}", expected.GetType().Name, ex.GetType().Name));
                    Assert.AreEqual(expected.Message, ex.Message, true, CultureInfo.InvariantCulture);
                }
                else
                {
                    Assert.IsTrue(expected.GetType().IsInstanceOfType(ex.InnerException), string.Format("Expected exception type: <{0}> Actual: {1}", expected.GetType().Name, ex.InnerException.GetType().Name));
                    Assert.AreEqual(expected.Message, ex.InnerException.Message, true, CultureInfo.InvariantCulture);
                }
            }
        }
    }

As you can see now the class has two overloaded methods, a generic and a non-generic versions. Also the names of both the class and the method changed so it reads a little bit better and finally both now support inherited exceptions.

This is what the use of this class will now look like:

        [TestMethod]
        public void ConstructorThrowsExceptionWhenArgumentsAreInvalid()
        {
           AssertException.Is<ArgumentNullException>("Value cannot be null.\r\nParameter name: number",
              new Func<int?, string, Foo>((num, name) => new Foo(num, name)),
              null, "any");

           AssertException.Is<ArgumentNullException>("Value cannot be null.\r\nParameter name: name",
              new Func<int?, string, Foo>((num, name) => new Foo(num, name)),
              1, string.Empty);

           AssertException.Is(new ArgumentNullException("name"),
              new Func<int?, string, Foo>((num, name) => new Foo(num, name)),
              1, string.Empty);
        }

        [TestMethod]
        public void MethodsThrowExceptions()
        {
            var firstFoo = new Foo(-5, "something");
            AssertException.Is<ApplicationException>("Number should not be negative",
               new Action(firstFoo.DoSomething));

            var secondFoo = new Foo(5, "something");
            AssertException.Is<DivideByZeroException>("Number cannot be divided by zero",
               new Action<int>(secondFoo.DoSomethingElse),
               0);
        }

        [TestMethod]
        public void FunctionsThrowExceptions()
        {
            var foo = new Foo(1, "invalid");

            AssertException.Is<InvalidCredentialException>("Authorization denied",
               new Func<bool>(foo.Validate));

            AssertException.Is<NullReferenceException>("Seriously Foo cannot be null",
               new Func<string, int?, Foo, Foo>(foo.GetNewFoo),
               "any", 3, null);
        }

As you can see the code now almost reads as regular English. It is still more verbose than the attribute option but we discussed the advantages and disadvantages of both approaches on the previous post.

So a couple of conclusions that I can get are that even though we may have a good solution for a particular problem we can always find inspiration and ideas to improve those solutions and we should always be humble enough to realize that our solutions could be improved, no matter how much we might like them.

The same as last time here you have several options to assert the message of exceptions in your unit tests. Use the one you consider the most appropriate. Happy coding.

If you do a quick google search you will realize a lot of people out there have the need to be able to unit test that a piece of code throws an exception with a specific message. Unfortunately the ExpectedExceptionAttribute attribute does not provide this feature. It does have a “message” parameter but its use is to define the message the developer will see when the test fails.

All the people with this need, myself included, have searched long and hard for a way to implement an attribute with this functionality or, at the very least, a way to execute this kind of test reliably and in a way that it can be reused consistently for each possible case.

Most implementations I have found are different flavors of catching the exception and comparing the type and message to an expected one, but they are limited in the number or type of parameters, or on the return type they support. I did once find the implementation of an attribute but was a little disappointed since I thought it was too much code for something as simple as the objective at hand. Let me be very clear about the fact that I am NOT saying this is a bad option nor am I discouraging its use in any way or form. I am only saying that, in my very personal opinion, it is too much code for something so simple and, it is code that you should understand how it works since you might have the need to maintain it.

So because of this I came up with another implementation by using delegates which is smaller than the attribute one and supports both actions and functions with as many parameters as needed. It does have the disadvantage though that its use might be a little cryptic. I always strive for code readability so decorating the test method with an attribute may be a little better. Here is the code, some examples on its use and, for completeness, a Foo class to test it:

This is the code that we are interested in:


public static class CustomAssert
{
   public static void IfExceptionIs(Exception expected, Delegate action, params object[] parameters)
   {
      try
      {
         action.DynamicInvoke(parameters);
         Assert.Fail(string.Format("Expected exception of type <{0}>; with message <{1}> but none was thrown.", expected.GetType().FullName, expected.Message));
      }
      catch (Exception ex)
      {
         if (ex is AssertFailedException || ex is AssertInconclusiveException) throw;

         if (ex.InnerException == null)
         {
             Assert.AreEqual(expected.Message, ex.Message, true, CultureInfo.InvariantCulture);
             Assert.AreEqual(expected.GetType(), ex.GetType());
         }
         else
         {
             Assert.AreEqual(expected.Message, ex.InnerException.Message, true,  CultureInfo.InvariantCulture);
             Assert.AreEqual(expected.GetType(), ex.InnerException.GetType());
         }
      }
   }
}

This would be the testing Foo class:

public class Foo
{
   private readonly int? _number;
   private readonly string _name;

   public Foo(int? number, string name)
   {
      if(!number.HasValue) throw new ArgumentNullException("number");
      if(string.IsNullOrEmpty(name)) throw new ArgumentNullException("name");

      _number = number;
      _name = name;
   }

   public void DoSomething()
   {
      if(_number < 0) throw new ApplicationException("Number should not be negative");
   }

   public void DoSomethingElse(int dividend)
   {
      if(dividend == 0) throw new DivideByZeroException("Number cannot be divided by zero");
   }

   public bool Validate()
   {
      if(_name == "invalid") throw new InvalidCredentialException("Authorization denied");
      return true;
   }

   public Foo GetNewFoo(string newName, int? newNumber, Foo oldFoo)
   {
      if(oldFoo == null) throw new NullReferenceException("Seriously Foo cannot be null");
      return new Foo(newNumber, newName);
   }
}

And this is how it would be used:

[TestMethod]
public void ConstructorThrowsExceptionWhenArgumentsAreInvalid()
{
   CustomAssert.IfExceptionIs(new ArgumentNullException("number"),
      new Func<int?, string, Foo>((num, name) =>; new Foo(num, name)),
      null, "any");

   CustomAssert.IfExceptionIs(new ArgumentNullException("name"),
      new Func<int?, string, Foo>((num, name) => new Foo(num, name)),
      1, string.Empty);
}

[TestMethod]
public void MethodsThrowExceptions()
{
   var firstFoo = new Foo(-5, "something");
   CustomAssert.IfExceptionIs(new ApplicationException("Number should not be negative"),
      new Action(firstFoo.DoSomething));

   var secondFoo = new Foo(5, "something");
   CustomAssert.IfExceptionIs(new DivideByZeroException("Number cannot be divided by zero"),
      new Action<int>(secondFoo.DoSomethingElse),
      0);
}

[TestMethod]
public void FunctionsThrowExceptions()
{
   var foo = new Foo(1, "invalid");

   CustomAssert.IfExceptionIs(new InvalidCredentialException("Authorization denied"),
      new Func<bool>(foo.Validate));

   CustomAssert.IfExceptionIs(new NullReferenceException("Seriously Foo cannot be null"),
      new Func<string, int?, Foo, Foo>(foo.GetNewFoo),
      "any", 3, null);
}

To have the complete picture here are some snippets on how would the tests look like if we were to use the custom attribute:


[TestMethod]
[ExpectedExceptionWithMessage(typeof(ArgumentNullException), "name")]
public void ConstructorThrowsExceptionWhenNameIsEmpty()
{
   new Foo(1, string.Empty);
}

[TestMethod]
[ExpectedExceptionWithMessage(typeof(ApplicationException), "Number should not be negative")]
public void MethodThrowsExceptionWhenNumberIsNegative()
{
   var foo = new Foo(-5, "something");
   foo.DoSomething();
}

Another thing to note is that the implementation I am proposing looks for an inner exception since sometimes the real problem might be hiding in there and the attribute one supports inherited exceptions. Both options could easily be added in either one.

So there you have it, two options to assert the message of an expected exception. Use the one you consider best for you, your team and your project and may your unit tests save you from grief and maintenance nightmares.