In the last years we’ve been hearing a lot about unit testing, so much that now is in the mouth of almost every big or small software company. It’s even so common that many are so brave to say: “If you don’t provide unit tests for your code, then it’s worthless”.
Well, I would be even more brave and say: “If you provide unit tests with your code, even your templates, those test should be worth a penny”.
I found this wonderful piece of code today from a project template:
[TestClass]
public class PackageTest {
[TestMethod]
public void CreateInstance() {
var package = new Walkthrough_01Package();
}
[TestMethod]
public void IsIVsPackage() {
var package = new Walkthrough_01Package();
Assert.IsNotNull(package, "The object does not implement IVsPackage");
}
[TestMethod]
public void SetSite() {
// Create the package
IVsPackage package = new Walkthrough_01Package();
Assert.IsNotNull(package, "The object does not implement IVsPackage");
// Create a basic service provider
OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices();
// Site the package
Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK");
// Unsite the package
Assert.AreEqual(0, package.SetSite(null), "SetSite(null) did not return S_OK");
}
}
Ok, let’s just rewrite this test for the sake of just see how would it look like:
public class SamplePackageFacts {
private readonly IVsPackage _package = new Walkthrough_01Package();
[Fact]
public void PackageCanCorrectlySetSiteFromProvider() {
var site = OleServiceProvider.CreateOleServiceProviderWithBasicServices();
var answer = _package.SetSite(site);
Assert.Equal(VSConstants.S_OK, answer);
}
[Fact]
public void PackageCanCorrectlySetNullProvider() {
var answer = _package.SetSite(null);
Assert.Equal(VSConstants.S_OK, answer);
}
}
Can you spot the problem? do you see any value at all in the original three tests methods?
NOTE: I used xUnit just because I like it. It’s not a problem inherited from using the test framework but from the way of look at what is a unit test, you could do exactly the same using MSTest.
