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: