Wednesday, November 19, 2008

Ubiquitous Assertion Syntax

One thing that really bothers me about testing is having various different assertion syntaxes. Take a look at the following JUnit examples. (don't worry, I'll be picking on Ruby and .net frameworks as well)

@Test public void simpleAdd() {
assertEquals(2, 1+1);
}

@Test(expected= IndexOutOfBoundsException.class) public void empty() {
new ArrayList<Object>().get(0);
}

In both tests I want to verify something; however the two tests use different mechanisms for verification. This adds pain for anyone reading or maintaining the test. When determining what a test is verifying you need to look for assertions as well as expected exceptions in the annotation.

When you start adding behavior based tests the situation gets even worse.

Mockery context = new Mockery();

@Test public void simpleAdd() {
assertEquals(2, 1+1);
}

@Test(expected= IndexOutOfBoundsException.class) public void empty() {
new ArrayList<Object>().get(0);
}

@Test public void forWorksCorrectly() {
final List<Integer> list = context.mock(List.class);

context.checking(new Expectations() {{
one(list).add(1);
one(list).add(2);
}});

for (int i=1; i < 3; i++) {
list.add(i);
}
}

Testing 1.0
3 different tests, 3 different ways to verify your code does what you expect it to. To make matters worse the mock expectations live in the body of the test, so there's no guarantee that when looking for assertions you only need to look at the last few lines of the test. Every time you encounter a test you must spend time looking at the test, top to bottom, and determine what is actually being tested.

The tests above are simple, it's a much bigger problem when a test uses a few different forms of verification.

Mockery context = new Mockery();

@Test(expected= IndexOutOfBoundsException.class) public void terribleTest() {
final List<Integer> original = new ArrayList<Integer>(asList(1, 2));
assertEquals(2, original.size());
final List<Integer> list = context.mock(List.class);

context.checking(new Expectations() {{
one(list).add(1);
one(list).add(2);
}});

for (Integer anOriginal : original) {
list.add(anOriginal);
}

original.clear();
original.get(0);
}

Okay, it would be terrible to run into a test that bad. You might work with people who are smart enough not to do such a thing, but it's very common to see tests that have both assertions and methods that are mocked. You may not consider mocked methods to be a form of verification, but if one of those methods isn't called as you specified it should be called, your test will fail. If it can cause your test to fail, it's a form of verification in my book.

In Java, there are at least 3 ways to define expected behavior, and often a test mixes more than one. This is not a good situation for a test reader or maintainer.

In the Ruby and .net worlds, the story isn't much better. The state based assertions are specified differently than the behavior based assertions; however, both Ruby and .net have a superior way of handling expected exceptions: assert_raises and Assert.Throws.

Below are similar tests in test/unit with mocha (Ruby), with an example of assert_raises for handling the expected exception.

def testState
assert_equal 2, 1+1
end

def testError
assert_raises(NoMethodError) { [].not_a_method }
end

def testBehavior
array = []
array.expects(:<<).with(1)
array.expects(:<<).with(2)
[1, 2].each do |number|
array << number
end
end

And, for the .net crowd, here's the NUnit + NMock version of the 3 types of tests. As previously mentioned, NUnit provides an assertion for expecting exceptions, but there's still a mismatch between the state based and behavior based assertions. (full disclosure, I don't have Visual Studio running on my Mac, so if there's a typo, forgive me)

private Mockery mocks = new Mockery();

[Test]
public void Add()
{
Assert.AreEqual(2, 1+1);
}

[Test]
public void Raise()
{
Assert.Throws<ArgumentException>(delegate { throw new ArgumentException() } );
}

[Test]
public void Behavior()
{
IList list = mocks.NewMock<IList>();

Expect.Once.On(list).Method("Add").With(1);
Expect.Once.On(list).Method("Add").With(2);

for (int i=1; i < 3; i++) {
list.Add(i);
}
mocks.VerifyAllExpectationsHaveBeenMet();
}

Testing 2.0
In each language there have been steps forward. Both Java and C# have moved in the right direction regarding placement of behavior based expectations. Ruby still suffers from setup placement of mock expectations, but at least the behavior based expectations follow the same assertion syntax that the state based assertions use.

In Java, the Mockito framework represents a step in the right direction, moving the mock expectations to the end of the test.

@Test public void forRevisited() {
List list = mock(List.class);

for (int i=1; i < 3; i++) {
list.add(i);
}

verify(list).add(1);
verify(list).add(2);
}

Likewise, in .net, Rhino Mocks allows you to use "Arrange, Act, Assert Syntax (AAA)". The result of AAA is (hopefully) all of your tests put their assertions at the end.

public void ForRevisited()
{
var list = MockRepository.GenerateStub<List>();

for (int i=1; i < 3; i++) {
list.Add(i);
}

list.AssertWasCalled( x => x.Add(1));
list.AssertWasCalled( x => x.Add(2));
}

These steps are good for the big two (Java & C#); however, I'd say they are still a bit too far away from ubiquitous assertion syntax for my taste.

RSpec represents forward progress in the Ruby community.

it "should test state" do
2.should == 1+1
end

it "should test an error" do
lambda { [].not_a_method }.should raise_error(NoMethodError)
end

it "should test behavior" do
array = []
array.should_receive(:<<).with(1)
array.should_receive(:<<).with(2)
[1, 2].each do |number|
array << number
end
end

RSpec does a good job of starting all their assertions with "should", (almost?) to a fault. It's not surprising that RSpec was able to somewhat unify the syntax, since the testing framework provides the ability to write both state based and behavior based tests. Looking at the tests you can focus on scanning for the word "should" when looking for what's being tested.

Unfortunately the unified "should" syntax results in possibly the ugliest assertion ever: lambda {…}.should raise_error(Exception). And, as I previously stated RSpec still suffers from setup placement of the mock expectation "should" methods. Perhaps RSpec could benefit from AAA or some type of test spy (example implementation available on pastie.org).

# this doesn't work, but maybe it should....

it "should test behavior" do
array = Spy.on []
[1, 2].each do |number|
array << number
end
array.should have_received << 1
array.should have_received << 2
end

Next Generation Testing (Testing 3.0?)
Eventually I expect all testing frameworks will follow RSpec's lead and include their own mocking support, though I'm not holding my breath since it's been two years since I originally suggested that this should happen. Today's landscape looks largely the same as it did 2 years ago. When testing frameworks take that next step, the syntax should naturally converge.

In the Ruby world you do have another option, but one with serious risk. I've been looking for ubiquitous assertion syntax for so long that I rolled my own framework in Ruby: expectations.

Expectations standardizes on both the location of your assertions (expectations) and how you express them. The following code shows how you can expect a state based result, an exception, and a behavior based result.

expect 2 do
1 + 1
end

expect NoMethodError do
[].no_method_error
end

expect Object.new.to.receive(:ping).with(:pong) do |obj|
obj.ping(:pong)
end

As a result of expectations implementation you can always look at the first line of a test and know exactly what you are testing.

Full disclosure: Before you go and install expectations and start using it for your production application, you need to know one big problem: there's no support for expectations. I'm no longer doing Ruby full-time and no one has stepped up to maintain the project. It's out there, it works, and it's all yours, but it comes with no guarantees.

In the .net and Java worlds, the future of testing looks less... evolved. In the .net world, the ever focused on testing Jim Newkirk has teamed up with Brad Wilson to create xUnit.net. xUnit.net represents evolution in the .net space, but as far as I can tell they haven't done much in the way of addressing ubiquitous assertion syntax. In Java, I don't see any movement towards addressing the issue, but can it even happen without closures (anonymous methods, delegates, whatever)?

I'm surprised that more people aren't bothered by the lack of ubiquitous assertion syntax. Perhaps we have become satisfied with disparity in syntax and the required full test scan.

Tuesday, November 18, 2008

Specialize in Something Relevant

generalist: a person competent in several different fields or activities
If you read my blog entry on Language Specialization you might have concluded that I prefer generalists. If, in our industry, generalists were what the definition describes, then I would prefer generalists. Unfortunately, business software developers seem to have created their own definition of generalist.
business software developing generalist: I know how to do the simplest tasks with many different languages/tools, but I can not be considered competent with any of them.
I blame Scott Ambler. To me anyway, it seems like the daft generalist movement started when Scott wrote Generalizing Specialists.

Our industry has always been saturated by bad programmers. I'm on record stating that at least 50% of the people writing business software should find a new profession. The problem with bad developers is that they take good ideas and turn them in to monstrosities.

I remember reading Generalizing Specialists and being inspired. I thought Scott gave fantastic and relevant advice. Unfortunately, many bad or junior developers heard: Don't bother to deeply understand anything, instead, you're agile if you know a little about everything. Suddenly, when I started interviewing developers I ran into situations like this.
  • me: So, I see you have Erlang on your resume, how do you like the language?
  • candidate: I like it's concurrency handling, but I'm a bit weary of it's syntax.
  • me: (thinking - okay, do you have any original thoughts on Erlang?) I can understand those points of view, what problem were you trying to solve with Erlang and why did you think it was the right tool?
  • candidate: Oh, I really only got through the 2 minute tutorial, you know, hello world basically. But if you guys have Erlang projects you want me to work on I'm happy to, I'm a generalist, I like all languages.
  • me: Okay, so what language would you say you know the most about?
  • candidate: I don't bother to specialize, I do a little bit with each language, you know, hello world or whatever, so I can use the right tool for the job. That's the best part of being a generalist.
  • me: (thinking - this interview is already over) Okay, so tell me about the languages/tools you've had to use at your different jobs?
Inevitably, the candidate doesn't even have a deep understanding of the tools they've used at work, because they are too busy doing hello world in every language invented. They also love to say that they take the Pragmatic Programmers advice to extreme and 'learn' several languages a year.

The truth is, these generalists have little in the way of valuable knowledge. They provide their projects with little more knowledge than a Google search can bestow in 30 minutes. In short, they're worthless, if not destructive.

I don't actually blame Scott Ambler. In my opinion he was right then, and he's right now. Become a Generalizing Specialist is still the advice that I currently give developers.

Specializing in something makes you an asset to the team. If I'm building a Web 2.0 website, I want everyone to have an understanding of HTML, CSS, Javascript, Ruby, & SQL. However, I also want each team member to specialize in one of those areas. Knowing IE quirks is just as important as knowing how to optimize MySQL. And, I want to make sure I have team members that can get into the deep, dark corners of delivering highly effective software. That doesn't mean everyone needs to know what a straight join in MySQL does, but at least 1 person should. The rest of the team isn't entirely off the hook though, they better understand how to write basic SQL statements that are maintainable and at least semi-performant.

Becoming a Generalizing Specialist takes time, but the first step is becoming a Specialist. Once you deeply understand one language/tool, you can move on to the next relevant language/tool. How do you know when it's time to move on? When you start having answers to questions that people aren't asking. If you're constantly looking up answers to common questions, you aren't a specialist. However, if you start providing more (relevant) detail in your answers than people are looking for, you're on your way to possessing the deep understanding that a Specialist should have. At that point, it's probably time to start looking deeply into something else.

One painful mistake to look out for is specializing in something less relevant. If you work for a trading firm that writes only thick client applications, understanding why Chrome's Javascript VM is better than Firefox's Javascript VM is probably not the best use of your time. It's true that you may move on to a web application at some point, but by then your information will probably have become stale anyway. Stick to specializing in things that you work with day to day. Your language, your IDE, the Domain Specific Languages you use in your applications (regular expressions, SQL, LINQ, etc), or the frameworks you use (Spring, ASP.net, etc) are things you should specialize in to increase the value you provide to your team.

Eventually, you become competent with several different tools and languages. You've become a Generalizing Specialist and as such you are significantly more valuable to your team.

Tuesday, October 21, 2008

Language Specialization

Didn't you just totally sell out? -- Obie Fernandez @ Rails Summit Latin America
Obie and I are good friends. He wasn't trying to insult me. I was talking about how much I liked my new job (at DRW Trading), and the different aspects of the job. One aspect of my job is that I spend a fair amount of my time working with Java. I do some C# and some Ruby also, but these days it's more Java than anything else. I believe Obie was genuinely curious if I felt like I sold out since I'm not doing Ruby full-time anymore.

It's an interesting question, but it comes packed with all kinds of assumptions. For the question to be valid, I would have had to trade something I truly care about for the combination of something I did and did not like. Luckily, that wasn't the case.

Obie isn't the first person to be surprised that I'm no longer working full-time with Ruby. Truthfully, I find it a bit funny that people think I would base a career move on a language. Ruby is my favorite language, but it's not the correct choice for every problem that needs to be solved. And, languages have never been my primary concern when deciding what job to take.

My first job primarily used Cold Fusion. When I joined AOL Time Warner I gave up Cold Fusion for PHP. When I joined IAG I gave up PHP for C#. And so on. As you can see, I've never been too tied to a language. I've always been most interested in learning and growing. I love jobs that help me improve my skills.

Chad Fowler talks about something similar. In the section "Don’t Put All Your Eggs in Someone Else’s Basket" of My Job Went to India, Chad says the following:
While managing an application development group, I once asked one of my employees, “What do you want to do with your career? What do you want to be?” I was terribly disppointed by his answer: “I want to be a J2EE architect.” ...

This guy wanted to build his career around a specific technology created by a specific company of which he was not an employee. What if the company goes out of business? What if it let its now-sexy technology become obsolete? Why would you want to trust a technology company with your career?
I think Chad got it right, but it's not just companies you shouldn't trust. I wouldn't base my career on any technology, whether it was produced by a company or an open source community.

I prefer jobs that allow me to learn new things. Think of it as job security -- I shouldn't ever be out-of-date when it comes to technology experience. Think of it as an investment -- everything I learn creates a broader range of experience that I can leverage for future projects or jobs. Think of it as experimenting -- by trying many different solutions I may find ways to combine them and innovate.

I've turned down several jobs that paid more or offered comfort. I've never regretted it. Your career is long and (as Chad says) you should treat it as a business. When you look at it from that perspective it obviously makes sense to spend the early years learning and deciding which is the best direction to take.

The truth is, if you focus on one technology you'll never be as good as your teammates who have more experience mixing technologies to produce the best solution.

As I told Obie, I definitely don't feel like I sold out. In fact, one of the reasons I joined DRW was because they use Java. I've never worked with Java, messaging, or the financial domain. Having experience with those 3 things will make me better. And, diversifying your experience will make you better as well.

Tuesday, September 30, 2008

Testing Dynamic Web Applications

At RailsConf Europe, in the Q & A portion of my talk on Functional Testing someone asked what I recommend for testing Javascript.

Ugh. Testing Javascript. Is it possible to recommend something when everything you've seen is terrible? Usually I'm cool with picking the tool that sucks the least, but when it comes to Javascript testing the only words that come to mind are: epic fail.

In the past I've failed in two different ways.
  • Selenium: Too slow and to brittle for any decent size test suite. There's more on that if you wish.
  • Some javascript unit testing framework. I can't even remember the name. The syntax was ugly, the tests weren't easy to write, and the runner didn't integrate with any automated tools we used -- lame.
My response in Berlin was "The pivotal guys are smart, so if I were going to try something new it would be Screw Unit." Of course, I just googled and found the RubyForge project and two with the same name on GitHub. I'm sure one of those is the current trunk.

A few days later it occurred to me what the correct answer was -- Don't use Javascript and you won't have to test it.

No, I'm not suggesting that we should all go back to mostly static websites. Static content is fine for some things, but GMail is an obvious example of a site that is better done dynamically.

However, Javascript isn't your only choice for highly dynamic websites.

These days, if I were writing a website that required any dynamic interaction I would absolutely use Flex or Silverlight. I've done Flex, and it was nice to work with, but I must admit that I'm lured to Silverlight because it's going to (or does already?) support Ruby.

I'm not sure what the Silverlight testing story is, but I found Flex (and ActionScript) to be quite testable. The single biggest win (as I've said before) is that I no longer need to do in-browser testing. Removing the browser from the equation is huge. No more IE bugs causing your tests to fail, no long start up times as the browser is run, etc.

Testing with FlexUnit (with it's drawbacks) is an order of magnitude better than any experience I've had testing Javascript.

I'm comfortable saying that I would still use Javascript for trivial features that provided so little business value that they did not warrant testing. However, any features that provide noticeable business value must be tested, and I would move to a RIA solution instead.

In my experience, the benefits of switching to a RIA solution are dramatic, one of the largest being: you no longer need to worry about testing Javascript.

Monday, September 22, 2008

When To Retire Your Brand

Building a brand takes a lot of effort, but I think the payoff justifies the investment. Having a strong brand definitely helped me find a fun and very well paying job. So now that I have a dream job (@ DRW Trading), what should I do with my brand?

I have to confess, I didn't start writing because I wanted share information. I started writing because I wanted to build a big brand, find a great job, and enjoy life. Somewhere along the way I began to enjoy writing and the positive results that came from knowledge sharing. Someone once said to me "I write better tests because of your blog". Obviously I was happy to hear that kind of feedback. At the same time it wasn't the reason I got started down this path.

I love to program. I also love to be in shape (which I'm not) and learn other languages (which I haven't been doing lately).

Now that I have my dream job, I've been spending more time doing the other things I love. Unfortunately, I found that between learning an interesting domain, going to the gym, and learning Italian, there's not much time left for blogging. I also find that since I'm doing all the things I love, I don't really like to be away presenting at conferences.

I thought it might be time to declare success on the brand building project, and move on to new pursuits... But, I was wrong.

The largest reason I can't quit writing and presenting is that I enjoy giving back to the community. Seeing a blog entry get 8,000 hits in one day causes an amazing feeling. Giving a presentation and getting feedback that says "Probably the best presentation at the conference" definitely makes you feel good about what you are doing. Seeing an idea become committed as the way to do something will definitely make you smile. I truly enjoy spreading ideas (or at least attempting to spread ideas) that help the community evolve.

Blogging and presenting also help me personally improve. The easiest way to get feedback on something is to put it out there. I considered several of my testing ideas to be "the right way" for far too long. Putting them down as blog entries resulted in further evolution of the ideas as well as a greater understanding of how context determines the correct approach. Simply writing about my ideas improves them. One thing we aren't short of is people to tell you you're wrong.

Your brand is also valuable to your employer. Employing people with name recognition improves your organization's ability to recruit talented new hires. This also directly benefits you, since you'll be given the opportunity to work with more talented teammates. At the moment, DRW is looking to hire the absolute best people in the industry. I wish I had an even stronger brand, so I could help attract the top talent.

Ultimately I came to the conclusion that building a brand is a career long activity. You can stop at any time, but getting that free time back comes at cost to your profession.