StructureMap: IRepository and Test Data Injection

I Love StructureMap! It’s wonderful. What a way to compose your code together easily,precisely, and consolidatedly (!!). When I put a sentence like that together, I wonderif I even know what I’m talking about. The problem with StructureMap, IoC, and dependencyinjection really seems to be that the jargon for the patterns is so manifestlytrue that once you learn what the hell you are doing, you are completelyunable to stop talking about it in shorthand. And that shorthand makes absolutelyno sense to someone who hasn’t absorbed the patterns. Keep plugging, people. Onceyou do it, you’ll get it. Then you’ll be there and not be able toexplain to other people why you’re so right. It’s like being Tom Cruise and needingto explain scientology.


I learned two things today. The first is how to hook all of my concrete generic repositorytypes together with their interfaces. I had been adding a line of configuration foreach repository. Now my test code looks like this:


And my production code:


That’s easy!

The other thing I learned is that I can happily and easily inject data into my objectregistry for testing purposes. I have an in-memory repository implementation built.All it needs is data.

public class MemoryDataSource{private Dictionary<Type, IQueryable> data;public MemoryDataSource(Dictionary<Type, IQueryable>data){ = data;}public IQueryable GetQueryable(Type type){return[type];}}public class ListRepository<T>: IRepository<T>{private MemoryDataSource source;public ListRepository(MemoryDataSource source){this.source = source;}public IQueryable<T> GetSource(){return ((IQueryable<T>)source.GetQueryable(typeof(T)));}public void SaveEntity(Tentity){return;}}

Now all I need to do is build a Dictionary<> keyed on the entity object typeand fill it up with data. Once I’ve done that, I just pass it into the StructureMapregistry like this:

ObjectFactory.Inject<Dictionary<Type, IQueryable>>(dataSource);

Now I can have ObjectFactory construct my object under test and it’s got just thedata I need it to have.

Test-Driven Learning Games and Tests

In my first and second poston the idea of learning Ruby through writing tests, I showed the basics of learninga language using the TDD tools. Since that start, I’ve found some great work othershave done along these lines that you can use to play with the skills you’re learningand test yourself against some real problems.

First, the Ruby Koans byJim Weirich are a comprehensive set of ‘learning tests’ that can teach you or quizyou on what you’ve learned of Ruby so far. Each time you pass a test, it points youto the next thing you need to fix. Truly TDD learning!

I was a bit put off when I first found this set, since it seems so much like a shortcut,but there’s no reason I can’t play with Jim’s tests as well as writemy own, now is there?

Second, there’s the Ruby Quiz, whichlooks to be a great place to get a graduate education in your Ruby skills. The quizisn’t being added to anymore, but the challenges are just awesome and they have referencesolutions from people who have solved them before you. Once you’ve solved one, youcan find so many ways of learning a better way. Talk about erudition!

A Testy Way of Learning Ruby

In my recentpost, I started sharing some of the fun of learning Ruby using Test-Driven techniquesto learn the language features and document what you are learning as you go.

There are several advantages of learning the language this way. It flexes your brainin ways that just reading the book or typing in the sample code doesn’t. Once you’redone, you have some running, organized code that you can refer back to. Also, whenyou upgrade your language, or change which platform you run it on, you can run yoursuite of learning tests. Find out if Ruby 1.9 is different from 1.8…and how. Are thereimplementation differences between linux Ruby and Iron Ruby? You’ll know.

Today, I’d like to cover the additional assert variants available in the Test::Unitmodule, and talk about using an IDE.

Lasttime, we covered the assert method for testing truth. But there are lot more thingsyou can test!

  • assert – Tests the truth of an expression
  • assert_block – Tests that the return value of a code block is true
  • assert_equal – Tests that two values are equal
  • assert_in_delta – Tests two floats with tolerance for floating point error (read upon this one! it’s a doozy)
  • assert_instance_of – Tests that an object is an instance of a class
  • assert_kind_of – Tests that an object is of a class, or a subclass, or implementsthe kind
  • assert_match – Test using a regular expression
  • assert_nil – Tests the nil-ness of the expression
  • assert_no_match – A not test
  • assert_not_equal – A not test
  • assert_not_nil – A not test
  • assert_not_same – A not test
  • assert_nothing_raised – A not test
  • assert_nothing_thrown – Not a test. Just kidding.
  • assert_operator – I don’t get this one. Well, I’m still learning!
  • assert_raise – Tests that the code block raises a given exception
  • assert_respond_to – Tests that an object has a named method defined
  • assert_same – Tests that both values are the same object instance
  • assert_send – Another one to learn on. Looks like it tests a method call?
  • assert_throws – Looks like another type of exception handling.

With this group of methods, it should be rather easy for you to write some nice, readabletests as you learn things up. One interesting one is assert_same, which can provethat all values of True are really the same instance. Also, when you write a testthat fails by raising an exception, use assert_raise to document that. You shouldhave a test that shows what happens when you divide by zero, and one that shows whathappens when you use an uninitialized variable.

Using an IDE

Most of the ‘True Ruby Folk’ believe with all their flinty hearts that you shouldn’tneed anything more than a charred and pointed stick to write excellent Ruby. Theyare probably right. On the other hand, a good IDE can be like a coding video gameand make the process so much more colorful and fun. I’ve sure found that JetBrains’new RubyMine IDE has made myearly Ruby coding a bit of clicky goodness.

Creating a new test class is really easy. You just add the file to your project:

You get a fully fleshed and voluptuous test class ready for you to have your way withit.

And while you’re learning the language, it’s really nice to have some code completionfeatures so that you can figure out the rest of what you’re typing without going madswitching between windows.

All that and it’s not going to break the bank. Just $99! Give it a try.

I hope you’re keeping up with your test writing. I’ve got 168 assertions testing languagefeatures and I’m just through the primitives and variable types.

How many tests can you write?

Test-Driven Learning

You may not have realized it, but learning Ruby is like being attacked by a bunchof ADD Buddhist Monks. They’ll jump into your living room, raving and excited, anddo back flips while telling you how Zen and relaxing development should be. It’s weird.

Once we’ve medicated the frenetic relaxation, though, it’s really evident that therea lot of good ideas to be found in this community. The latest that I’ve discoveredis Test-Driven Learning.

What this means to me is that I can FINALLY stop writing ‘Hello World’ programs. Languageshave print or printf or puts commands—we can stop being thrilled by that now. Ok?Let’s just write Tests! If we can make test Assertions, we can kick the tires of eachnew piece of language syntax we learn as we learn it without creating silly, baroqueprograms to host them.

Lets start out by discovering the shortest syntax to use the language’s testing framework.The one built into Ruby is Test::Unit. This is easy in Ruby. You need a ‘require’line and to subclass the test fixture class.

require "test/unit"
class TestTest< Test::Unit::TestCase
def test_tests
assert true

That’s easy. And now you can assert things. Like ‘true’. Save that in a file, like‘test.rb’ then execute it with the ruby command line.

C:UsersjoshDesktop> ruby test.rb
Loaded suite test_test
Finished in 0.001seconds.
1 tests, 1 assertions, 0 failures, 0 errors

From here on out, just start adding ‘assert’ lines as you discover things about Ruby.Since we started with ‘true’, maybe some asserts on Truth would be a good start. Iwonder which of these will pass and which will fail? If you know Perl, Javascript,or C# your preconceptions will be different.

assert true
assert false
assert 'True'
assert ""
assert 0
assert 1

So little code, and now you can curl up with your favorite Ruby howto book and spenda warm afternoon pondering the nature of Truth. Exciting eh? Well calm down! You don’tneed to be a crazy Zen guy. Just do some learning.


What’s on my development laptop?

Fingerprints. A little peanut sauce. A Cthulu ’08 sticker (why vote for the LesserEvil?).

Oh yeah. I also have these program which are little anthropomorphized series of datawhich fight each other to death on a giant battlefield inside my computer in orderto keep Norton Antivirus from controlling my internet connection. I’ve upgraded mymain computers to Vista x64 (UAC OFF!), mainly because I like pain. Now that I’vebeen hostage to Vista for a while, I must say this about my captor: it’s not as asbad as people say. As long as you’ve got a steaming hot lap warmer with 4gb of RAM,it performs just fine and with UAC off, it’s not really annoying. Second….I don’tknow what MS was thinking with this thing. It’s got exactly ONE feature that I givea sh– about as a user. For all of the pain of a new operating system and Microsoft’scompulsion to MOVE EVERYTHING AROUND SOMEWHERE ELSE,Vista doesn’t really offer much to give you a better user experience. I like the command/search/launcherbox in the Start Menu. That’s it. That’s the only reason I don’t just run back togood old XP. One feature.

Anyways. We were talking about tools….

Development Tools

  • Notepad++: MonolithicIDEs and design surfaces and friendly talking A.I.s notwithstanding, coding is stillabout text. Notepad++ is a solid replacement for the pathetic text editor dumped inthe O.S. by ‘One Feature’ Vista. Syntax highlighting. Regex search and replace. Tabs.If I’m not in Visual Studio, I’m editing text in Notepad++.
  • TortoiseSVN: All of the ‘new developer’resources I read seem to beg their readers to use source control. I was using sourcecontrol before I started working in code. Having a system that backs up your information…andit’s changes…is magic. The amount of pain saved for very light cost is amazing.TortoiseSVN is a windows UI for the Subversion source control system. I use hostedSVN at Beanstalk even though it’s simple to run your own repository. A couple of bucksa month is a bargain value for not worrying about the safety of your data.
  • CodeRushand Refactor Pro!: Currently I use CodeRush primarily for it’s templating engine.I think this is because I’m a bit too lazy to figure out a code generator. I may needto give that a little bit of thought. I like MyGeneration,but it’s CSLA templates seemed to be inadequate for my needs…perhaps I haven’t paidthe right attention. Anyways. CodeRush is like Code Snippets on Spinach! At the flickof your fingers it creates classes and properties and all of the boilerplate codethat we seem to write constantly in our development processes.  Writing in ahigh-ceremony language like C# can be a pain. CodeRush takes the pain away. And itdoes a million other things as well. CodeRush will amaze you in your first 10 minutes.And then you’ll still be learning amazing new things months later.
  • Nullsoft Installer System: I starteddeploying my projects with the MSI project built into Visual Studio. Maybe it wastoo wizardy. Maybe I just never learned how it worked well enough. The fault was probablymine. However, what I ended up with was installers that wouldn’t upgrade to new versions,that were overly complex, and that I had to manually work with in deploying. NSISis an installer from a simpler day. It zips all the files together and then copiesthem to where they belong on the users system. Some simple scripts define the filesto include, where to put them, and where to put shortcuts. Upgrading is simply aboutrunning a newer version installer. Building is as simple as running a script. NSISmade my deployments simple and understandable.
  • NUnit: Test Driven Development seemsto be talked about everywhere these days. It’s an awesome methodology for making bettercode. I don’t do that. TDD means writing well architected code from scratch, all thetime. I’m not sure what well-architected code is yet. I keep learning new things,and I’m coming along, but starting with perfection is a bit hard for now. However,Test-Enabled Development? I can see if the things I’m writing without firing up aGUI or IIS. I can make changes and check for breakage. I can refactor. And…well…makingtests makes me thing about how my code could be better designed. Occasionally I doa little Test Refactored Development. That just makes me a better coder.
  • Telerik RadControls: The basic .NET controlsleave your application looking so generic, and while you can develop serious functionality,it’s a lot of work. Telerik’s UI controls make your product look beautiful, and mostadvanced functionality is just a matter of doing a good data binding. Grab your CSLA.NET objects, and you’re riding a giant rocket mounted to a railway sled! Exhilarating. 
  • Mailbee .NET: I have barely used these, butI bought them to create a IMAP automation tool, and the result was quick, easy, andreliable. If your application needs to interact with email, I recommend these components.They aren’t very expensive, and the developer keeps updating them (updates are freefor the folk who have paid).
  • StyleCop: Code which iswritten to a formatting standard is easier to read, faster to understand, and saferto change. I’m not particularly religious about the Code Style you choose, but youshould have one. Style Cop takes the uncertainty out of the process, since it hasa ‘OneMicrosoft Way‘ standard style for you to use, and it will check your code foryou. Start checking your code with it, and your code will look better for the process.Plus it gives you some cool busywork to do, when you’re staring blankly at your screenafter the boss yells at you for showing up late to work after you chase that rabbitaround all night.

That’s my list for now. There’s more stuff added  to it all the time. The focusof the next installment will be selecting the proper athame and grimoire for writinga daemon. Or maybe something having to do with cake.