Thursday, November 4, 2010

XmlTidy

Needed a tool to tidy some Xml in "Programmer's Notepad" and could not resist to created my own version of XmlTidy. :-)

using System;
using System.Xml;
using System.Xml.XPath;

namespace XmlTidy
{
    public class Program
    {
        private enum ExitCodes
        {
            Success = 0,
            Failure = 1
        }

        private static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                return ShowUsage();
            }

            var inputFile = args[0];
            var outputFile = args.Length == 1 ? args[0] : args[1];
            return Tidy(inputFile, outputFile);
        }

        private static int ShowUsage()
        {
            Console.WriteLine("Usage: XmlTidy <inputfile> <outputfile>");
            Console.WriteLine("if <outputfile> is not specified, the <inputfile> is overwritten.");
            return (int)ExitCodes.Success;
        }

        private static int Tidy(string inputFile, string outputFile)
        {
            var result = (int)ExitCodes.Success;
            try
            {
                var document = new XPathDocument(inputFile);
                var settings = new XmlWriterSettings { IndentChars = "\t", Indent = true };
                var writer = XmlWriter.Create(outputFile, settings);
                document.CreateNavigator().WriteSubtree(writer);
                writer.Close();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                result = (int)ExitCodes.Failure;
            }

            return result;
        }
    }
}

Share:

Wednesday, November 3, 2010

Programmer's Notepad

Got a new laptop today and have started to install all the cool and useful tools I need. Previously I have used TextPad and Notepad++ as my notepad replacements, but this time I decided to see if there was some other text editors out there. Found "Programmer's Notepad" that looks promising. I looks simple and clean, but yet powerful.
Share:

Tuesday, October 19, 2010

Creating a self-signed certificate with private key

Needed to make a self-signed certificate with a private key for a project I working on. After some research I found that the combination of makecert and pvk2pfx did the trick. Use the following commands in Visual Studio Command Prompt
makecert -r -pe -n "CN=Test" -b 01/01/2010 -e 01/01/2020 -sky exchange Test.cer -sv Test.pvk
pvk2pfx.exe -pvk Test.pvk -spc Test.cer -pfx Test.pfx
When executing the commands above you will be asked for some information like password etc. After you are finished the file Test.pfx includes a self-signed certificate with the a private key.
Share:

Monday, October 11, 2010

Friday, October 1, 2010

Howto create unit test for privat, internal, and friend methods

Problem: You have a class with a private method that you wish to test.
public class ClassUnderTest
{
  private int DoSomePrivateStuff()
  {
     // Something is happening here
  }
} 
Since the method is private you can not access the it from the outside of the object.

How I solved this earlier was to make a testable class that inherited from the class I wanted to test.
public class TestableClassUnderTest : ClassUnderTest
{
  public int DoSomePrivateStuff()
  {
     base.DoSomePrivateStuff();
  }
} 

I now could do the following.
[TestClass]
public class ClassUnderTestTests
{
  [TestMethod]
  public void DoSomePrivateStuff_WhenCalled_ReturnsZero()
  {
     //Arrange
     var testClass = new TestableClassUnderTest();
     //Act
     var actual = testClass.DoSomePrivateStuff();
     //Assert
     Assert.AreEqual(0, actual);
  }
}

This is the classic Extract and Override pattern and there is nothing wrong with it.
But as a colleague showed me today, there is another way when you are using Visual Studio.
  1. Goto the ClassUnderTest in visual studio and right click. Select "Create Private Accessor" and select the test project you want this accessor in.
  2. Go to the test project you choose in step 1. You will now have a project folder called "Test References" with one file ending with ".accessor".
And that's it. VS have now created a class for you with the name "_accessor" that you can use in your tests. My example from above can now be rewritten to the following:
[TestClass]
public class ClassUnderTestTests
{
  [TestMethod]
  public void DoSomePrivateStuff_WhenCalled_ReturnsZero()
  {
     //Arrange
     var testClass = new ClassUnderTest_accessor();
     //Act
     var actual = testClass.DoSomePrivateStuff();
     //Assert
     Assert.AreEqual(0, actual);
  }
}
What's nice about this is that you don't need to create a bunch of testable classes. They are automagically created with reflection for you. Now you got more time to do fun stuff.... :-)

You can read more about this here: http://msdn.microsoft.com/en-us/library/bb385974.aspx

Share:

Wednesday, September 29, 2010

Testing exceptions in unit test

NUnit has a nice feature (Assert.Throws) that makes it possible to assert that a exception is thrown inside some code.

Visual Studio Unit Testing Framework seem to miss this feature and to check that the correct exception is thrown you would could use the following code:
[TestMethod]
public void WithTryCatch()
{
    // Arrange
    ApplicationException actualException = null;

    // Act
    try
    {
        ThrowSomeException();
    }
    catch (ApplicationExceptionex)
    {
        actualException = ex;
    }

    // Assert
    Assert.IsNotNull(actualException);
    Assert.AreEqual("Message", actualException.Message);
}

ExpectedExceptionAttribute
Using the ExpectedExceptionAttribute is possible. In the example below you expect a exception of type ApplicationException with the message set to "ExceptionMessage". All derived exceptions from ApplicationException will also satisfy the test.
[TestMethod]
[ExpectedException(typeof(ApplicationException), "ExceptionMessage", true)]
public SomeTest()
{
    DoSomething();
}

ExceptionAssert
The ExpectedExceptionAttribute could be enough in many situations. But it will not make you able to test specific attributes on an exception or the value of its inner exception. So why not make things it a little easier and more flexible with a helper class.
[TestMethod]
public void WithHelperClass()
{
    // Arrange
    // Act
    // Assert
    ExceptionAssert.Throws<ApplicationException>(
        () => ThrowSomeException(),
        ex => Assert.AreEqual("Message", ex.Message));
}
The Throws method catches the exception specified and will run the asserts on it. If no (or wrong) exception is thrown the test will fail.

The source code for the helper class can be found below.
[DebuggerStepThrough]
public static class ExceptionAssert
{
 /// 
 /// Asserts that an exception of type T is not thrown
 /// 
 /// >Typeparam name="T">Exception to look for
 /// Action to execute
 public static void DoesNotThrow<T>(Action action) where T : Exception
 {
  if (action == null)
  {
   throw new ArgumentNullException("action");
  }

  Exception actualException = null;
  try
  {
   action();
  }
  catch (T ex)
  {
   actualException = ex;
  }

  if (actualException != null)
  {
   throw new AssertFailedException(String.Format(
    "ExceptionAssert.DoesNotThrow failed. Exception <{0}> thrown with message <{1}>",
    actualException.GetType().FullName,
    actualException.Message));
  }
 }

 /// 
 /// Asserts that an exception is not thrown
 /// 
 /// Action to execute
 public static void DoesNotThrow(Action action)
 {
  DoesNotThrow(action);
 }

 /// 
 /// Asserts that an exception of type T is thrown
 /// 
 /// Exception to look for
 /// Action to execute
 public static void Throws<T>(Action action) where T : Exception
 {
  if (action == null)
  {
   throw new ArgumentNullException("action");
  }

  Exception actualException = null;
  try
  {
   action();
  }
  catch (Exception ex)
  {
   actualException = ex;
  }

  ValidateThrownException<T>(actualException, null);
 }

 /// 
 /// Asserts that an exception of type T is thrown
 /// 
 /// Exception to look for
 /// Action to execute
 /// Additional assert to be made on the exception
 public static void Throws<T>(Action action, Action<T> asserts) where T : Exception
 {
  if (action == null)
  {
   throw new ArgumentNullException("action");
  }

  Exception actualException = null;
  try
  {
   action();
  }
  catch (Exception ex)
  {
   actualException = ex;
  }

  ValidateThrownException(actualException, asserts);
 }

 /// 
 /// Asserts that an exception of type T is thrown
 /// 
 /// Exception to look for
 /// Action to execute
 /// Additional assert to be made on the exception
 /// Cleanup action to be executed.
 public static void Throws<T>(Action action, Action<T> asserts, Action finalAction) where T : Exception
 {
  if (action == null)
  {
   throw new ArgumentNullException("action");
  }

  Exception actualException = null;
  try
  {
   action();
  }
  catch (Exception ex)
  {
   actualException = ex;
  }
  finally
  {
   if (finalAction != null)
   {
    finalAction();
   }
  }

  ValidateThrownException(actualException, asserts);
 }

 /// 
 /// Valdidates the exception
 /// 
 /// Exception type to look for
 /// Exception to validate
 /// Additional asserts to be made on the exception
 private static void ValidateThrownException<T>(Exception actualException, Action<T> asserts) where T : Exception
 {
  if (actualException is T)
  {
   if (asserts != null)
   {
    asserts(actualException as T);
   }
  }
  else if (actualException == null)
  {
   throw new AssertFailedException(String.Format(
    "ExceptionAssert.Throws failed. No exception was thrown. Expected <{0}>.",
    typeof(T).FullName));
  }
  else
  {
   throw new AssertFailedException(String.Format(
    "ExceptionAssert.Throws failed. Expected <{0}>. Actual <{1}>",
    typeof(T).FullName,
    actualException.GetType().FullName));
  }
 }
}

Share:

Wednesday, September 15, 2010