20100918

Dependency Injection Using Nested Classes

In my day job (lately it seems to be a 24 hour day) I do most of my work in C#, and all our new projects are implemented using Test Driven Development. Like most people doing TDD, we need to inject mock/stub/dummy objects into our objects under test. The traditional way to accomplish this is either via Constructor Injection or Setter Injection.

I have never been a fan of using setters to inject test objects, because it clutters the code with properties and methods that are only used for testing and are never used by production code. At first, I relied on constructor injection, but would sometimes run into cases where I was passing in half a dozen or more objects into the constructor. Many of these objects were simply helper classes that bundled up some functionality needed by the object under test only, and would never normally be used outside of that class.

Over the last year we have evolved another way of injecting mock objects into our test objects – Nested Class Injection (or as we call it, “TestHook Injection”). In C#, a nested class has access to it's containing class's private members, so we can use methods on the nested class to reach into the private details of the outer class. Here is a simple example:

    public class ObjectUnderTest {

private IHelperObject _helper;

public ObjectUnderTest() {
_helper = new ProductionHelper();
}

public bool MethodToTest(int testNumber) {
return _helper.HelperMethod(testNumber);
}

public abstract class TestHook {

public static void InjectObjectHelper(ObjectUnderTest objectUnderTest, IHelperObject helper ) {
objectUnderTest._helper = helper;
}

}
}


Now all the test related code is contained within the abstract TestHook class. This class acts like the diagnostic connector on your car, allowing access to internal data and manufacturer's info without exposing it to the user. In fact, you can even use conditional compilation to exclude the TestHook class in the release build to remove the “connector” if code size or security is an issue.

Now when you are ready to test your objects, you can do something like:
        [Test]
public void Test_MethodToTest() {
ObjectUnderTest objectUnderTest = new ObjectUnderTest();

IHelperObject mockHelperObject = new MockHelperObject();
ObjectUnderTest.TestHook.InjectObjectHelper(objectUnderTest, mockHelperObject);

objectUnderTest.MethodToTest(12);

// Test expectations here...
}


Note that I do not normally create my own mocks as shown above, I typically use Rhino Mocks to create mock objects, and Ninject as my IoC container. The contrived examples above are just to show the basic technique of using a nested class to cleanly access the internals of an object for testing purposes.

Now injecting objects like this is really only useful when those objects are only going to be used internally by the class under test. If you need to pass in an instance of an object that is shared between multiple objects, traditional constructor or setter injection is fine, since that is actually part of the object's contract with the world.

We have been using this technique for several months now, and it has resulted in cleaner production code, and more streamlined testing. Our test setup methods are simpler now, because we only need to inject mocks in the tests that need them instead of in the common test setup method.

I figured I should write this up since I have found the technique very useful, and a quick Google search didn't turn up anything useful. I expect this can be used in any language that supports nested classes where the nested class has access to the outer class's private member variables. Let me know in the comments if you find this technique helpful, or have any improvements. Thanks for stopping by!

Read More......

20100516

Me Day

As a special treat for myself, I recently escaped from the Teknynja Cave to visit JPL's 2010 Open House. This was my first time visiting Jet Propulsion Laboratory or the open house event, and it was even better than I expected. As a science and space enthusiast, there where plenty of things to see. What I didn't expect was the festival atmosphere and all the activities and displays for kids and families. There was plenty of booths selling kettle corn, hamburgers & hot dogs, frozen lemonade and other treats, and the smells were like that of any “normal” festival.




My first stop of the day was the Space Flight Operations Facility, the “Mission Control” room, where spacecraft like the Viking, Pioneer, Voyager and the Mars Rovers have been monitored and controlled. It was exciting to see this room with so much history (and to be in the presence of so many computer monitors).






Next up was a short shuttle bus trip to the 25 Foot Space Simulator facility, a giant environmental chamber that simulates the conditions found in space or on other planets. Spacecraft are placed inside the simulator and subjected to the vacuum and heat of space. You can walk around inside the huge chamber, and I also enjoyed checking out the control room for the simulator.




One of the highlights of my trip was visiting the Spacecraft Assembly Facility, a enormous clean room where JPL's probes and landers are built. It was especially exciting for me to see the Mars Science Laboratory (still in several pieces), which is scheduled to arrive on Mars in 2012.



The big draw for me though, was the Hubble Wide Field Planetary Camera 2 exhibit, which displays the actual camera that flew on the Hubble telescope from 2002 until 2009. Being this close to actual space hardware was an amazing experience! It is difficult to really see it in this photo, as it is enclosed in a protective nitrogen gas environment. This exhibit is the centerpiece of the new museum on the JPL campus, that contains dozens of models of probes, rovers, and landers.



At this point in my visit, the lines were starting to get very long, but I didn't mind. My next stop was the Spacecraft Fabrication Facility, where the components for spacecraft are machined and manufactured. The amount of manufacturing and machining technology in this building is overwhelming, and the tables showing example parts was very impressive.



I finally ended up at the Micro Devices Laboratory, where they do everything from create nano-sized machines to electronic chip fabrication. There was plenty to see there, but this room caught my eye - this would be my dream office, with wires and electronic equipment everywhere. Maybe someday...







I wrapped up my trip taking in the architecture and the festival scene before hitting the “gift shop” to pick up a tee shirt and some swag for the kids. I really only hit about half the activities at the open house, but saw what I came to see and more. I'll have to go again, and next time I'll probably bring the young'ins along as well.

Read More......

20100307

std::string and sprintf

Amongst the many projects I am currently juggling, one of them involves developing some C++ code for an embedded Linux project. I've just hit an instance where I'd like to be able to use “printf” style formatting using std::string instances, but it can be pretty clumsy – I need to allocate buffer space for sprintf, invoke the function, and package up the result into another string.

I did a quick search on the Internet and found many others looking for the same thing: “Is there a way I can use sprintf in c++ using std:strings?” And invariably the answers were either


  • “No”

  • “Use std::ostringstream and c++'s built-in manipulators”

  • “Use boost::format

And they are all right!

It turns out that you can't safely use the *printf style variable argument lists with C++, as only POD (Plain Old Data) types can be passed in the list. Attempting to pass most other types will result in a segmentation fault at run time. The official C++ way is to use ostringstream and the usual stream manipulators to format parameters, but for me, that make's writing tests more difficult because I need to “build” the expected streams exactly the same way in my test code. The final method could work for me, except that this is an embedded project and I am trying to keep the number of libraries referenced to a minimum, since I need to build and include them on my target Linux system.

So my solution was to accept the limitations of the printf function and write a wrapper function that hides the buffer setup and string creation:

#include <string>
#include <stdarg.h>
#include <stdio.h>

string FormatString(const string& format, ...) {
char buffer[1024];

va_list arglist;
va_start(arglist, format);
int length = vsnprintf(buffer, sizeof(buffer), format.c_str(), arglist);
va_end(arglist);

return string(buffer, length);
}



I've tucked this away in a nested namespace so I can invoke it easily when needed. Now when I need formatted text I can just supply a c string or std::string format and my parameters, and get back a nice std::string instance in return. But there's a catch! I can't pass in a std::string as a parameter because the old-school c variable argument list can't handle objects. If I try to do that, I will get a “warning: cannot pass objects of non-POD type 'struct std::string' through '...'; call will abort at runtime” warning and a segmentation fault at runtime. The work around (at least for std::string objects) is to invoke the c_str() method on the string parameter instance. So for example

    string argument = "a string instance";
string result = FormatString("I can format a %s parameter!", argument.c_str());


allows me to supply std::string arguments as well. The c_str() function returns a pointer to a temporary buffer containing a c style string version of the string object's value.

So now I have my template style formatting and I can move on with my project. This project is my first foray into any substantial C++ programming, so if you seen any glaring problems or know a better solution, or if this little tip helped you too, please let me know by leaving a comment.

Read More......
 
Template design by Amanda @ Blogger Buster