Posterous theme by Cory Watilo

Filed under: TDD

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 wonder if I even know what I’m talking about. The problem with StructureMap, IoC, and dependency injection really seems to be that the jargon for the patterns is so manifestly true that once you learn what the hell you are doing, you are completely unable to stop talking about it in shorthand. And that shorthand makes absolutely no sense to someone who hasn’t absorbed the patterns. Keep plugging, people. Once you do it, you’ll get it. Then you’ll be there and not be able to explain to other people why you’re so right. It’s like being Tom Cruise and needing to explain scientology.

Anyways.

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

ForRequestedType(typeof(IRepository<>)).TheDefaultIsConcreteType(typeof(ListRepository<>));

And my production code:

ForRequestedType(typeof(IRepository<>)).TheDefaultIsConcreteType(typeof(LlblRepository<>));

That’s easy!

The other thing I learned is that I can happily and easily inject data into my object registry 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)
{
this.data = data;
}

public IQueryable GetQueryable(Type type)
{
return this.data[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(T
entity)
{
return;
}
}

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

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

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

Test-Driven Learning Games and Tests

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

First, the Ruby Koans by Jim Weirich are a comprehensive set of ‘learning tests’ that can teach you or quiz you on what you’ve learned of Ruby so far. Each time you pass a test, it points you to 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 write my own, now is there?

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

A Testy Way of Learning Ruby

In my recent post, I started sharing some of the fun of learning Ruby using Test-Driven techniques to 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 brain in ways that just reading the book or typing in the sample code doesn’t. Once you’re done, you have some running, organized code that you can refer back to. Also, when you upgrade your language, or change which platform you run it on, you can run your suite of learning tests. Find out if Ruby 1.9 is different from 1.8…and how. Are there implementation differences between linux Ruby and Iron Ruby? You’ll know.

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

Last time, we covered the assert method for testing truth. But there are lot more things you 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 up on 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 implements the 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, readable tests as you learn things up. One interesting one is assert_same, which can prove that all values of True are really the same instance. Also, when you write a test that fails by raising an exception, use assert_raise to document that. You should have a test that shows what happens when you divide by zero, and one that shows what happens when you use an uninitialized variable.

Using an IDE

Most of the ‘True Ruby Folk’ believe with all their flinty hearts that you shouldn’t need anything more than a charred and pointed stick to write excellent Ruby. They are probably right. On the other hand, a good IDE can be like a coding video game and make the process so much more colorful and fun. I’ve sure found that JetBrains’ new RubyMine IDE has made my early 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 with it.

And while you’re learning the language, it’s really nice to have some code completion features so that you can figure out the rest of what you’re typing without going mad switching 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 language features 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 bunch of ADD Buddhist Monks. They’ll jump into your living room, raving and excited, and do 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 there a lot of good ideas to be found in this community. The latest that I’ve discovered is Test-Driven Learning.

What this means to me is that I can FINALLY stop writing ‘Hello World’ programs. Languages have 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 each new piece of language syntax we learn as we learn it without creating silly, baroque programs 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
end
end

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:\Users\josh\Desktop> ruby test.rb
Loaded suite test_test
Started
.
Finished in 0.001
seconds.
 
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. I wonder 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 spend a warm afternoon pondering the nature of Truth. Exciting eh? Well calm down! You don’t need to be a crazy Zen guy. Just do some learning.

Resources:

What's on my development laptop?

Fingerprints. A little peanut sauce. A Cthulu '08 sticker (why vote for the Lesser Evil?).

Oh yeah. I also have these program which are little anthropomorphized series of data which fight each other to death on a giant battlefield inside my computer in order to keep Norton Antivirus from controlling my internet connection. I've upgraded my main computers to Vista x64 (UAC OFF!), mainly because I like pain. Now that I've been hostage to Vista for a while, I must say this about my captor: it's not as as bad 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't know what MS was thinking with this thing. It's got exactly ONE feature that I give a sh-- about as a user. For all of the pain of a new operating system and Microsoft's compulsion to MOVE EVERYTHING AROUND SOMEWHERE ELSE, Vista doesn't really offer much to give you a better user experience. I like the command/search/launcher box in the Start Menu. That's it. That's the only reason I don't just run back to good old XP. One feature.

Anyways. We were talking about tools....

Development Tools

  • Notepad++: Monolithic IDEs and design surfaces and friendly talking A.I.s notwithstanding, coding is still about text. Notepad++ is a solid replacement for the pathetic text editor dumped in the 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 source control before I started working in code. Having a system that backs up your information...and it'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 hosted SVN at Beanstalk even though it's simple to run your own repository. A couple of bucks a month is a bargain value for not worrying about the safety of your data.
  • CodeRush and 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 need to 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 paid the right attention. Anyways. CodeRush is like Code Snippets on Spinach! At the flick of your fingers it creates classes and properties and all of the boilerplate code that we seem to write constantly in our development processes.  Writing in a high-ceremony language like C# can be a pain. CodeRush takes the pain away. And it does 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 started deploying my projects with the MSI project built into Visual Studio. Maybe it was too wizardy. Maybe I just never learned how it worked well enough. The fault was probably mine. 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. NSIS is an installer from a simpler day. It zips all the files together and then copies them to where they belong on the users system. Some simple scripts define the files to include, where to put them, and where to put shortcuts. Upgrading is simply about running a newer version installer. Building is as simple as running a script. NSIS made my deployments simple and understandable.
  • NUnit: Test Driven Development seems to be talked about everywhere these days. It's an awesome methodology for making better code. I don't do that. TDD means writing well architected code from scratch, all the time. 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 a GUI or IIS. I can make changes and check for breakage. I can refactor. And...well...making tests makes me thing about how my code could be better designed. Occasionally I do a little Test Refactored Development. That just makes me a better coder.
  • Telerik RadControls: The basic .NET controls leave 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 most advanced 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, but I bought them to create a IMAP automation tool, and the result was quick, easy, and reliable. 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 free for the folk who have paid).
  • StyleCop: Code which is written to a formatting standard is easier to read, faster to understand, and safer to change. I'm not particularly religious about the Code Style you choose, but you should have one. Style Cop takes the uncertainty out of the process, since it has a 'One Microsoft Way' standard style for you to use, and it will check your code for you. 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 screen after the boss yells at you for showing up late to work after you chase that rabbit around all night.

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