Wednesday, January 30, 2013

Learning JustMock for Working with Nasty Dependencies

Update: I totally forgot to give mad props to colleague and good pal Phil Japikse for walking me through a couple things over IM in the course if noodling all this out.

I’ve given my Unit Testing 101 talk ten or 20 times over the last four or five years and I love it. I enjoy getting folks introduced to unit testing without having to deal with dogma issues around Test Driven Development, Test Occasionally Development, etc.

Part of the talk hits up working with mocking in order to get past a dependency on external providers. The example I use is a security provider used to check whether or not the current user’s authorized to update info for an employee.

In the past I’ve used Rhino.Mocks to work through this. I’ve used Rhino in a few projects over the years and it’s been a great tool for me.

Being the rather dense guy I am, I forgot that the awesome company I work for has its own mocking tool: JustMock. I figured it made sense to alter my tests to work with JustMock, if for no other reason than I could speak halfway intelligently to questions on it from other folks I interact with in the community.

One of the things I was most interested in was dealing with badly handled dependencies in code. The example I used previously had a nice constructor-injected interface-based security provider, so it was easy and clean to handle with Rhino. Here’s how it looks:

public class EmployeeUpdater
{
    private readonly IUpdateEmployeePermissible _updateEmployeeSecurityProvider;
 
    public EmployeeUpdater(
        IUpdateEmployeePermissible updateEmployeeSecurityProvider)
    {
        _updateEmployeeSecurityProvider = updateEmployeeSecurityProvider;
    }
 
    public Employee UpdateEmployeeRate(Employee targetEmployee, float newRate)
    {
        Employee updatedEmployee;
        if (_updateEmployeeSecurityProvider.
            CanUpdateEmployeeRate(targetEmployee.EmployeeId))
        //if (true)
        {
            updatedEmployee = new Employee(
                targetEmployee.EmployeeId, 
                targetEmployee.FirstName,
                targetEmployee.LastName,
                targetEmployee.Address, newRate);
        }
        else
        {
            throw new SecurityException(
                "Invoking user doesn't have permissions to update target target employee. " +
                                        targetEmployee);
        }
        return updatedEmployee;
    }
}

A test using Rhino, complete with interaction verification, is straightforward:

[Test]
public void Verify_security_provider_is_called()
{
    int userId = 1;
    int oldRate = 5;
    int newRate = 10;
 
    var mockProvider = MockRepository.GenerateMock<IUpdateEmployeePermissible>();
    mockProvider.Expect(x => x.CanUpdateEmployeeRate(userId)).Return(true);
 
    Employee current = new Employee(userId, "Jim", "Holmes", "Doghouse", oldRate);
    EmployeeUpdater updater = new EmployeeUpdater(mockProvider);
 
    Employee updated = updater.UpdateEmployeeRate(current, newRate);
 
    mockProvider.VerifyAllExpectations();
}

I took and muddied up the EmployeeUpdater a bit to mimic code we’ve either written ourselves or have seen: “new”ing up objects instead of injecting them, and using calls to static methods or classes. These situations make it tough to mock things out and will force you to move to a commercial mocking tool like TypeMock or JustMock. [1] (JustMock has an extremely powerful free version, but mocking concrete classes, “future mocks” of items “new”ed up instead of injected, or static requires the commercial version.)

Here’s my uglified EmployeeUpdater class. I simply created two different methods, one which newed up the security provider in it, another which hit the provider via a static call.

public class EmployeeUpdaterLegacyStyle
{
    public Employee UpdateEmployeeRate_ProviderNewedUpHere(Employee targetEmployee, float newRate)
    {
        UpdateEmployeeSecurityProvider _updateEmployeeSecurityProvider =
            new UpdateEmployeeSecurityProvider();
 
        Employee updatedEmployee;
        if (_updateEmployeeSecurityProvider.
        CanUpdateEmployeeRate(targetEmployee.EmployeeId))
        //if (true)
        {
            updatedEmployee = new Employee(targetEmployee.EmployeeId,
                targetEmployee.FirstName,
                targetEmployee.LastName,
                targetEmployee.Address, newRate);
        }
        else
        {
            throw new SecurityException(
                                        "Invoking user doesn't have permissions to update target target employee. " +
                                        targetEmployee);
        }
        return updatedEmployee;
    }
 
    public Employee UpdateEmployeeRate_ProviderIsStaticHere(Employee targetEmployee, float newRate)
    {
        Employee updatedEmployee;
        if (UpdateEmployeeSecurityProvider_Static.CanUpdateEmployeeRate(targetEmployee.EmployeeId))
        //if (true)
        {
            updatedEmployee = new Employee(targetEmployee.EmployeeId,
                targetEmployee.FirstName,
                targetEmployee.LastName,
                targetEmployee.Address, newRate);
        }
        else
        {
            throw new SecurityException(
                                 "Invoking user doesn't have permissions to update target target employee. " +
                                        targetEmployee);
        }
        return updatedEmployee;
    }
}

JustMock handles both quite nicely. First, working with “future” mocking to handle the variant that instantiates the object in the method. Note I’m working with a concrete class. No interfaces, no virtual, just a straight concrete class that’s instantiated right in my method above. The final mockedProvider.Assert() validates the security provider’s method was indeed called by the updater. (Comment out the //if(true) portion in the updater to see that test fail!)

public void Mocking_provider_newed_in_method()
{
    int userId = 1;
    int oldRate = 5;
    int newRate = 10;
 
    var mockedProvider =
        Mock.Create<UpdateEmployeeSecurityProvider>();
    //Standard syntax for mocking
    //Mock.Arrange(() => 
    //    mockedProvider.CanUpdateEmployeeRate(userId))
    //        .IgnoreInstance()
    //        .Returns(true)
    //        .Occurs(1);
 
    //using the fluent interface from JustMock.Helpers 
    mockedProvider.Arrange(x => x.CanUpdateEmployeeRate(userId))
                  .IgnoreInstance()
                  .Returns(true)
                  .Occurs(1);
 
    Employee current =
        new Employee(userId, "Jim", "Holmes", "Doghouse", oldRate);
    EmployeeUpdaterLegacyStyle legacyUpdater =
        new EmployeeUpdaterLegacyStyle();
    
    Employee updated = 
        legacyUpdater.UpdateEmployeeRate_ProviderNewedUpHere(current, newRate);
 
    Assert.AreEqual(updated.HourlyRate, newRate);
    //Standard assert
    Mock.Assert(mockedProvider);
    //Fluent from Helpers
    mockedProvider.Assert();
}

Here’s a test handling the static call variant above:

[Test]
public void Mocking_provider_called_statically()
{
    int userId = 1;
    int oldRate = 5;
    int newRate = 10;
 
    Mock.SetupStatic(typeof(UpdateEmployeeSecurityProvider_Static),
        StaticConstructor.Mocked);
 
    bool called = false;
    Mock.Arrange(() => 
        UpdateEmployeeSecurityProvider_Static.CanUpdateEmployeeRate(userId))
        .Returns(true)
        .Occurs(1);
 
    Employee current =
        new Employee(userId, "Jim", "Holmes", "Doghouse", oldRate);
    EmployeeUpdaterLegacyStyle legacyUpdater =
        new EmployeeUpdaterLegacyStyle();
 
    Employee updated = 
        legacyUpdater.UpdateEmployeeRate_ProviderIsStaticHere(current, newRate);
 
    Assert.AreEqual(updated.HourlyRate, newRate);
    Mock.Assert(() => 
        UpdateEmployeeSecurityProvider_Static.CanUpdateEmployeeRate(userId),
        Occurs.Exactly(1));
}

I’m sure there are better ways to leverage JustMock, and I’m sure there are cleaner ways to write the test. This exercise was more about me learning what capabilities JustMock has so I could keep it somewhat clear in my own head.

I’d love to hear feedback from folks who’ve worked with both mocking tools! Have you worked with Rhino.Mocks and JustMock? Have any thoughts?

[1]Perhaps Rhino.Mocks now handles these situations. I fully admit I haven’t kept up with it…

Monday, January 14, 2013

CodeMash Financial Planning Sheet

UPDATED

Interested in more detail on how we plan CodeMash? Want to see all the gory (and scary!) financial figures behind the scenes?

We’ve posted up the exact Excel sheet I use to plan everything financial around CodeMash. If you’re a conference organizer, or considering organizing one, then this sheet may be of great use to you. Yes, it’s tailored to CodeMash, but it’s full of information that may be very useful to you. There are a number of things it helps me with every year:

  • Meal planning: I’m able to keep track of the various meals, plus I have some notes around what I need to make sure gets covered. (Think proteins for vegetarians, greens at each meal, etc.)
    • Fixed versus consumable costs: Planning conferences starts off as “We’ll get awesome sessions and have fantastic people!” and inevitably turns to “Crap. How am I going to organize and pay for all this food?” If you’re organizing a conference you absolutely have to keep a careful eye on your food costs. I break out fixed costs (per head things like meals and party food) versus consumable (variable) costs like soda, coffee, and drinks. Those consumable costs terrify me because the impact can be thousands of dollars.
  • AV costs: Tracking Kalahari and external vendor AV costs helps me ensure I’ve got the right count of projectors, microphones, and screens ordered to cover every day.
  • Attendee gifts: I use this as a checklist to help ensure I’ve got shirts/hoodies, USB sticks, etc. ordered up.
  • Psuedo-TODO List: All the items on the various tabs serve to remind me of some of the various things we have to ensure get covered.

The workbook isn’t perfect. I refactor it every year based on things I’ve learned (usually the hard way). Just this year I finally deleted out columns I’d had hidden which contained revenue and estimated expenses for attendee headcounts of 250, 400, 500, and 700. It’s been a few years since we were that small…

Still, it’s invaluable for me in planning. It may be of interest to you, and it follows CodeMash’s policy of being as transparent as possible around our finances.

Grab it here! I hope you find it useful and informative!

UPDATE: I didn’t make clear that this workbook is not finalized for 2013. Consumables (soda, coffee, cocktails and beer) always are a huge variable, and there are always a bunch of last minute charges/changes. That $31K surplus will be nowhere near that by the time things are said and done.

Sunday, December 16, 2012

My Trip to India

I’ve returned this last Wednesday from 12 days in India and I thought I’d post a few musings on the trip here. (I’ve already posted up some of the work-related things over at my “day job” blog.)

Without a doubt this was one of the most impactful overseas trips I’ve ever had, and I’ve been to a fair number of places outside North America over my life: Okinawa, France, Saudi Arabia, Panama, the Philippines, St. Martin, England, Italy, Hungary, Austria, Poland, Bulgaria, and a likely a few others I’m forgetting.

I did zero preparation for the trip. None. Normally my wife and I are huge planners. We get all kinds of research done for big trips and have lots of things lined up. This time I figured I’d just go over and jump in the deep end and float wherever currents took me. Good choice.

First some of the bad things: India is a country where 300 million people live below poverty, and in India, unlike the US, poverty means poverty. People sleeping on blankets in the dirt with a torn tarp over their head poverty. 20 story five star hotels with tent cities next to them poverty. Hideous water giving you instantaneous dysentery and hepatitis poverty. It’s staggering if you’ve been in similar situations before, mind-numbingly shocking if you haven’t. The piles of trash across the entire country are sad—India is a land of amazing beauty and deep, deep spirituality. It was heartbreaking to see such a wonderful place being used as a dumping ground.

But still…

You get past that, or at least find yourself able to move beyond it, and wow, what India has to show you! Noise, color, smells, sounds, noise, people, food. The list goes on and on and on.

The Food

Food in India is a wonderful experience. India, like Italy, Spain, and Mexico, isn’t one style of cuisine. How could it be? Like those other nations India comes from a very diverse, fragmented history. The food in the south was greatly different from that of the north, and all of it was great. I was lucky to have friends to explain some of the differences to me.  As you’ve likely noticed if you’ve followed this blog for long, I’m a pretty serious foodie, so when I run across stuff like this in the street I’m in love!

IMG_0654

Or when my colleague takes me to a spot like this for dinner on the trip back from Agra:

IMG_0676

This was a dinner from a central region of India which wasn’t typical of Bangalore, but my pal DJ thought I’d enjoy it. How right he was!

2012-12-03_20-23-08_702

Here’s a milk drink we had at a diner-like place in Delhi.

2012-12-10_15-15-28_746

My stomach was in fairly good shape the entire trip, but then I eat a lot of spicy food already so my stomach was somewhat preconditioned. It was pretty amusing how so many of my colleagues and fellow diners there would continually ask “Is this too spicy for you? Are you OK with this?” I suppose I’m a bit atypical in this area, though… (That said, the street food at the cart above did do me in a bit. I knew better, but didn’t care.)

The People

The people are perhaps the happiest, most open, most hospitable I’ve ever come across in any of my travels. Bavarians previously held that spot, but my experiences in India blew even that away. Indians are gracious and full of laughter. I was honored to be invited into two different homes for meals, and they were some of the best times I had. (Being invited into someone’s home for food has a special significance for me, one I’m not able to explain well. Suffice it to say it means a lot.)

Indians are incredibly communal people. You might be taken aback at the depth conversations go between complete strangers. During our 16 hour day trip to Agra, my bachelor colleague got a grilling on his bachelorhood status, advice on why he should marry, and insight on a successful life—all from the middle-aged driver who we’d just met that morning at 6am. Get over the personal boundaries you might have and just enjoy the fact that Indians love people and want to know more about you.

They’re also extraordinarily happy. I had some great meals with various people through the developer and tester communities, and all were filled with laughter and jokes. And good food.

I was also amazed at the forward thinking mindset of the testing professionals I spoke with. India earned a reputation (partially justly) for cheap labor of poor quality. You need to lose that perception of them, right now. The people I spoke with at conferences, user groups, and customer sites were, for the vast majority, serious about taking their work to the next level. They’re looking at the long game, and they’re committed to making serious value-based transformations in how they do their work. I had some amazing conversations there that got me fired up and excited.

the traffic

Traffic in India is non-stop. Traffic is simply an insane, chaotic, wonderful experience if you can let go of any notion of patience. It will take you two hours to travel 60Km in Delhi, and 1.5 hours to go 15Km in Bangalore. Getting frustrated and angry won’t solve a thing, so just sit back and enjoy the tuk tuk (powered three wheeler rickshaw) or cab ride. Don’t freak out that you’ve got a two inch space between your vehicle and the huge dump truck next to you. The driver’s thinking “I had an inch and a half to spare!”

Scooters are family transportation vehicles in India, and you’ll see amazing sights: pipes, furniture, groceries, and more folks than you would think could fit on a two wheeler. Personal favorite: Dad driving, mom on back, puppy in mom’s lap. Personal record: Dad driving, mom near back, four other kids scattered from handlebars to tail end. Yes, six on a two wheeler…

It seems insane to someone from the West, but it’s similar to what I’ve experienced in my previous trips to Panama, the Philippines, etc. You’d think there would be non-stop wrecks, mayhem, and fatalities, but I didn’t see a single accident while I was there. I saw a lot of scratched up, dinged up cars, but not one wreck. Indians understand the implicit system with the traffic, and they, as with so many other things in their nation, just figure out how to have huge numbers of people co-exist in small spaces. With cars. And scooters. And trucks. And pedestrians. And dogs. And tuk tuks.

The horns

Horns require a section of their own. Honking was non-stop in Bangalore, prevalent in my countryside drives, and moderate in Delhi. If you sit back and listen the honking has an entertaining language all of its own.

There’s the single, quick “toot” which is the equivalent of “Coming up on your right/left. Make way, please!” A bit longer “honk” might be used of the person the driver’s passing didn’t move out of the way quickly. Toots escalate through honks up through blaaats to the rarely used Angry Honk where the driver’s really frustrated. My first driver for my day trip to Mysore had a very light, happy honk. I didn’t like the driver for our Agra trip very much. He was Angry Honk right off the bat all day.

The Sights

Where to start? India is full of so many strange, wonderful, overwhelming things. Yes, yes, the Taj Mahal is teh awesum, but you expect that. It’s the Taj Mahal.

IMG_0638

What was more impactful to me were some of the more intimate, less visited temples. I was at a temple near Mysore that was built in 849 that really moved me. This palace below with a shrine to a holy man is a short hour from Agra, and I had one of the best times there.

IMG_0659

There’s also the crazy IT market in Delhi that is straight out of some cross between a peyote-hammered steampunk and MC Escher.

2012-12-10_17-08-25_804 2012-12-10_17-20-22_755

All of this can just drive you crazy trying to take it all in. I stopped taking pictures very early in my trip, choosing to just absorb a lot and get a few pictures in here and there. I think that was a pretty smart choice.

Wrapping Up

I’m really thankful I got the chance to go to India. I’m already trying to line up a return trip or two. I can’t wait to get back and see new old friends and new old sights.

Tuesday, October 16, 2012

Handling Rejection (From Conferences)

Sometimes it seems like a significant part of my day job is having my submissions to various conferences rejected. Off the top of my head, here’s an incomplete list of conferences where I’ve had submissions rejected from over the last year(ish)

  • TechEd
  • DevConnections
  • DevLink
  • Agile Testing Days
  • Agile Dev Practices
  • StarEast/StarWest
  • Some testing conference in London whose name I’ve forgotten

There are a number of other conferences as well, but frankly I’ve lost track.

Rejection stings, for certain, but I have also come to view these rejections as a pretty good learning opportunity. After I get over the pain of rejection, that is.

First off, I always thank the organizers for considering my submissions. I can’t imagine how many hundreds of submissions conferences like DevConnections or StarEast/West get. Taking a moment to thank the content selection crew is simply good manners. (TechEd is different. It’s a total black box, impersonal process, so I never get any contact with humans.)

Secondly, I sit back and think about what might have been the cause for getting passed over. If possible, I try to get feedback directly from the selection folks; however, that’s not always possible.

I’ve found there are a number of useful aspects to consider:

  • Content doesn’t fit. Maybe you’ve just missed the mark with your submissions to that conference. Some years ago I tried wedging a testing talk to an open source conference targeted more to business application developers. My abstract simply didn’t make a good case why the talk would fit in their conference. Make sure what you’re submitting will be useful to the conference organizers.
  • Content lost in the chaff. You need to submit talks that stand out from all the others. “Intro to MVC” is outdated and doesn’t offer up anything unique from the 20 other MVC talks the organizers are looking through. Make a clear case of what value your session brings to the attendees.
  • Content selection crew was overwhelmed. Poorly organized conferences might have too few folks on staff to get a good review in. If you’re not known to the organizers, then they may have simply lost you in the tidal wave of submissions. Networking matters. Experience matters. (I’m very thankful that the CodeMash content chairs works hard to scale out the selection crew every year to avoid just this problem. They still have huge amounts of work.)
  • Poorly written abstract. It happens, even to someone who’s polished and submitted hundreds of abstracts over the last ten years. I’d like to think I’ve learned and don’t do this anymore, but it’s possible. I once wrote another blog post with some thoughts about writing a good abstract.
  • Better submissions from other folks. That happens on occasions, particularly for really large conferences. Look at what did get picked up and compare your submissions to those. Note that you’ll have to do some serious stepping back and viewing things with complete self-honesty and detachment. You can’t let your own pride get in the way with false impressions. Which brings me to…
  • Ego. Yes, sometimes my own ego gets in the way of submissions. Last year I put in four testing talks to a regional conference. None got accepted. Looking back I think I seriously slacked off when writing the abstracts because I felt I was well-known enough that the talks would get picked up anyway. That one stung but good—however, it was a good lesson learned. Respect yourself enough to put aside your ego and care about what you’re putting in. Remember, it’s not about you.
  • Drama. Conference organizers are horribly, insanely busy during planning and especially during execution of the conference. The last thing they need is drama or worries about unreliability. If you’re a Drama Queen or King, or if you’re a flake, then you’ve got a deep, deep hole to dig yourself out of. Getting over that can take years because that sort of trust is hard to rebuild. (As a personal note, seven years ago I bailed from a half-day workshop at a conference put on by my pal Chris Woodruff. I bailed the day before the conference. It’s perhaps the worst I’m a Douchebag moment of my adult life, and I’m still beating myself up about it. Thankfully Chris is an awesome guy who was extraordinarily gracious about it, and I think I’ve somewhat atoned for it by now.)

Rejection’s not easy. I’ve gotten three rejection notices in the last two weeks alone. That said, view it as an opportunity to avoid lashing out and instead consider how you can improve for the next conference you target.

I’m already working on a few more submissions now…

Subscribe (RSS)

The Leadership Journey