How to make some things mockable

Posted on January 8, 2008

Suppose I want to test something, but there is no supported way to do this.

For example I have a method that uses base class method RenderText to display JSON skipping the view. I would really like to capture the output to make sure that correct string is generated. Regular testing techniques did not work in this case. So here is a simple solution.

1. Create an interface that will mimic the methods of base class you want to test.
2. Implement that interface in your base class.
3. In the base class create a property of interface type and create a mutator to allow you to set new instance.
4. In the Base class constructor set this property to this class instance.

Example in code:

class ClassWithMethodIwantToTest
    void RenderText(string);

interface InterfaceIwantToMakeTastable
    void RenderText(string);

class MyBaseClass extends ClassWithMethodIwantToTest implements InterfaceIwantToMakeTastable
     InterfaceIwantToMakeTastable SomeVariable
           get;
           set; 

     Constructor MyBaseClass()
         SomeVariable = this;

class MyRealClassThatWillRuleTheWorld extends MyBaseClass
     void SomeMethod()
           SomeVariable.RenderText("i'm ok!");

And now in your test you can provide mocked version of the InterfaceIwantToMakeTastable and capture information you need.

Because I change the structure of my code and make it more complex just to make it testable, this is the case where I would have liked to have ability to provide custom version of the method to a class instance. But hey it’s better then untested code!

Filed Under Uncategorized | 2 Comments

2 Comments so far
  1. 00strange January 9, 2008 15:49

    Wow…this sounds fucked up…. nice man!

    look @ video on youtube i did… such stupid shit in contrast…
    http://youtube.com/watch?v=R_40fcvdB8o

  2. Iouri January 11, 2008 16:59

    This is not your video.

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name

Email

Website

Comments

© Copyright 0xDEADBEEFCAFE • Powered by Wordpress • Design by Sebastin.

free web hit counter