views:

288

answers:

1

I'm trying to unit test some code that calls into VirtualPathUtility.ToAbsolute

Is this possible with the unit testing tools provided with VS 2008.

+3  A: 

Static classes and methods are really hard to work with in unit tests (which is one reason why i try to avoid them). In this case, I would probably develop a wrapper around the static class, containing just those methods that I use. I would then use my wrapper class in place of the real class. The wrapper class would be constructed so that it is easy to mock out.

Example (sort of) using RhinoMocks. Note that it uses dependency injection to give the class under test a copy of the wrapper. If the supplied wrapper is null, it creates one.

public class MyClass
{
     private VPU_Wrapper VPU { get; set; }

     public MyClass() : this(null) {}

     public MyClass( VPU_Wrapper vpu )
     {
         this.VPU = vpu ?? new VPU_Wrapper();
     }

     public string SomeMethod( string path )
     {
         return this.VPU.ToAbsolute( path );
     }
}

public class VPU_Wrapper
{
    public virtual string ToAbsolute( string path )
    {
         return VirtualPathUtility.ToAbsolute( path );
    }
}

[TestMethod]
public void SomeTest()
{
     string path = "~/path";
     string expected = "/app/path";

     var vpu = MockRepository.GenerateMock<VPU_Wrapper>();
     vpu.Expect( v => v.ToAbsolute( path) ).Return( expected );

     MyClass class = new MyClass( vpu );

     string actual = class.SomeMethod( path );

     Assert.AreEqual( expected, actual );

     vpu.VerifyAllExpectations();
}
tvanfosson
+1 for wrapping it, that said I prefer to explicitly declare an interface for stuff I will mock like that
eglasius
@Freddy -- I often use an interface as well.
tvanfosson