The interruptible programmer

A read a good blog post about learning to workĀ interrupted. Ā Work 2.0 ā€“ the interruptible programmer. Ā The blogger had to learn to switch from a conventional, anti-interruption, get in ‘the mode’ then stay there for as many hours as possible, to a take frequent breaks mode due to health problems. Ā  It was interesting since the majority of my career I’ve been exposed to the frequent interruptions style of working and have been aspiring for the non-interruptions style in order to improve throughput.

At my old job, I used to handle a plethora of queries. Ā Support phone calls would come through distracting me from programming. Ā I also used to keep my ears open for conversations about areas of the software or business I knew about so as to be able to help my colleagues avoid taking a wrong, time-consuming path as they were scoping out ideas for solutions to business / technical problems. Ā These too were distractions that I had to learn to shut out.

At my new job, there are still distractions but an order of magnitude less than what my old job was. Ā No phone on my desk, or MSN chat allowed means that the only real distractions are from my boss, some seldom queries from a fellow dev or product manager, and then emergency support queries from the business when all the other developers are away that are even more seldom.

Adjusting to this new way has been a little harder than I initially thought. Ā I was used to being interrupted. Ā The benefit of being interrupted often was that I wouldn’t get ‘locked on’ to a problem. If I was stuck, something would happen by chance to distract me so that when I came back I had pondered a way forward in the background. Ā It was so run of the mill that I didn’t realise how much it became part of my daily routine.

At my new job, I found I’d get stuck on a problem and then keep pondering and pondering on it without a way forward thanks to the seemingly productive ‘one thing at a time’ mentality. When faced with a hard problem, I had to learn to deliberately leave a problem be for a little while and re-employ the task switching skills I’d learnt at my previous job. Here is a crazy analogy: Work is not a sausage that you can split in half and then continue eating the other half later. Ā Some parts of eating the sausage wear you out, and you need to cut up into smaller chunks so you can chew through it.

The blogger however reminds me of my current boss, who I must say is exceptional at task switching in the face of constant business and colleague distractions (or at least able to do frequent task switching without complaining about loosing context). Ā It was good to have a working example to think about whilst reading the blog. Ā It seems that the best tricks to employ are, to one, not get upset that you are being distracted, and two, keep some context of what you are doing, so that when you switch you have something you’ve written down to come back to. Ā The blog post makes mention of GTD as well which is good to see.

Junit Kungfu

A great presentation with audio that talks about Junit 4, test naming and other things.Ā  I liked this presentation because it starts expression Behaviour Driven Development concepts without actually using a Behaviour Driven Development Framework.Ā  Additionally its one of the more in-depth presentations covering the new features of JUnit like Rules.

The presenter is John Ferguson Smart who runs testing and agile tools bootcamps around Australia and NZ (as well as elsewhere) so if you are in the vacinity you should consider looking into em.

My notes from the presentation:

Naming tests

Dont use the name testXXX ā€“ you arenā€™t testing methods of your code

You are testing use cases ā€“ what should your class be doing

Take out private methods, maybe extract to a separate class and test those separately if they are getting too big.

Use the word should.Ā  Express an outcome

Class Name: When is a behaviour applicable
Method Name: When at is the behaviour testing

Tests become more readable.

Arrange-Act-Assert

Create the test collaborators – Inputs and Expected Outputs (Arrange)

Test the behaviour (Act)

Verify behaviour is correct (Assert)

Extending Hamcrest Matchers

Combine matchers together ā€“ hasItem(someOtherHasPropertyMatcherYouPreviouslyDefined)

Create a new matcher ā€“

  1. Extend TypeSafeMatcher<type of thing you are checking against)
  2. Implement Constructor take inĀ  a matcher of expected value
  3. Implement matchesSafely(type of thing you are checking against)
  4. Implement describeTo ā€“ decorate the existing test result/matcher descriptionā€¦Ā  description.appendText(ā€œWuzUp!ā€); matcher.describeTo(Description);
  5. Create a Factory Class for your matchers with static factory methods to return a new matcher
  6. Use It

Multiple asserts per test are bad (see also Integration Tests are a Scam)

You can combine hamcrest matchers into one test

assertThat(itesm, allOf(hasSize(1), hasItem(ā€œjavaā€)));

assertThat(itesm, hasSize(greaterThan(1)));

The error messages will be cleaner too ā€“ expect list size of one, and has item java but received <blah>

Parameterized Tests

Usually just one test per Parameterized test class ā€“ they get run once

Ways to get test data

Use an xls spreadsheet source

Use Selenium 2ā€™s WebElement to get a webpage

@FindBy(name="HD_EN") WebElement importerName;
@FindBy(name="HD_EA") WebElement importerAddress;
@FindBy(name="HD_ER") WebElement importerRepresentative;

// getters and setters
Ā // getter return importerName.getValue();

// setter
public void setImporterName(String value) {
     enter(value, into(importerName));
}

Smoke test to make sure getters and setters are correct

image

Make sure the annotations arenā€™t wrong

JUnit Rules

Delete folders after test run

@Rule public TemporaryFolder folder = new TemporaryFolder()
folder.newFile(ā€œa file nameā€);

ErrorCollection,

accumulate errors rather than fail on first.Ā  This saves having to write 20 different tests with large setup that check 20 things on the same page (eg login and load webpage table then verify each cell)

@Rule public ErrorCollector collector = new ErrorCollector();
// in your test
Ā collector.addError(new Throwable(ā€œblahā€));
collector.addError(new Throwable(ā€œsomething elseā€));
collector.checkThat(result, yourMatcher);

The result will show ā€œblahā€, ā€œsomething elseā€ and the result of your failed matcher, as well as fail the test.

TimeoutRules

When you know something should have a short response time, a DAO for example should be shorter than 1 second

@Rule public MethodRule globalTimeout = new Timeout(1000);
@Test public void catchInfiniteLoopInTest() { for(;;); }

Catch any major issues before they get into production and become embarassing

Verifier Rule

Something that happens after a test is completed, like an assert

Inject behaviour to make JUnit add checks after each testā€¦. kind of like a test post-condition or invariant from Betrand Meyers OO Software construction, but just for the tests themselves.

private List<String> systemErrorMessages = new ArrayList<String>();
@Rule
public MethodRule verifier = new Verifier() {
    @Override
    public void verify() {
        assertThat(systemErrorMessages.size(), is(0));
    }};

A good example I see would be using it to tie up mock verification calls in EasyMock

Watchman Rule

Called when a test fails or succeeds.Ā  Additional logging perhaps?Ā  How about restarting a GUI, or take a screenshot when a test fails.

Categories

Group tests in your own hierarchy based on your classification of the test rather than writing test suites.Ā  Performance testsĀ  that integration tests.Ā  Slow running or fast running tests?

You can setup plain old normal interfaces for your categories, and have them extend each other via subclassing.Ā  There is no Junit annotation here to indicate its an interface for testing, so you can potentially use any interface in your source.Ā  Iā€™m not sure if this is good practice or not, but say you wanted all your DAO tests that implemented a GenericDAO to be tested, you could do thisā€¦. or how about test all classes that implements Serializable?

You can annotate a test class, or tests methods with @Category(InterfaceName.class)

When running a category suite however you still need to include the classes to inspect as well as the category name.

@RunWith(Categories.class)
@IncludeCategory(PerformanceTests.class)
@SuiteClasses( { CellTest.class, WhenYouCreateANewUniverse.class })
public class PerformanceTestSuite {}
You can also exclude from a Run and run a
@RunWith(Categories.class)
@ExcludeCategory(PerformanceTests.class)
@SuiteClasses( { CellTest.class, WhenYouCreateANewUniverse.class })
public class PerformanceTestSuite {}

But how about scanning your whole test bed?Ā  Can we programmatically inject suite classes and use them with Categories?Ā  At this point it is a limitation unless you want to use a classpath hack.

Parallel Tests

If you have fast IO and multicore (like my new work PC Smile) and well written tests that donā€™t trodd on each others data.

U use Mavenā€™s surefire 2.5 plugin to achieve this, and say methods, classes or both in parallel.Ā  Classes is probably safer since most people write the test slipping thru later tests in the same class depend on earlier test methods accidentally.

Infinitest

This is a tool for IntelliJ and Eclipse that runs tests when you save your source and tells you if you have failed runs.Ā  I remember twittering about how cool this would be if it existed a while back, and Iā€™m glad I wasnt the only one with this idea and that someone actually implemented it Open-mouthed smile.

Also there was a plugin for IntelliJ called Fireworks but I could never get it to run tests properly on my Windows PC; always complaining about not being able to find a JDK home Sad smile.

This tool seems pretty cheap at $29 for an individual license, Iā€™ll check it out and give it a shot.

http://improvingworks.com/products/infinitest/

What would be super cool is if it worked with Categories mentioned above, to be able to exclude GUI tests from being executed.Ā  There may be a feature in Infinitest that handles it but Iā€™d be keen to see.

Mockito

Iā€™m traditionally an EasyMock guy but Mockito has always had good buzz.Ā  At my new job we dont actually have a mocking framework yet so Iā€™m keen to give it a look.

Mockito seems to have less verbose setup of tests, something that when learning EasyMock bashed me around a bit ā€“ ever forget to get out of record mode and get a green test accidentally.

As per Integration Tests are a scam ypresso recommends, you can verify interactions, verify a method is being called with certain params.

Other Stuff (comments from the Q&A of the presso)

Hibernate mappings ā€“ use an in-memory database

FEST asserts ā€“ an alternate to Hamcrest that avoids the Generic issues that plague Hamcrest!!! (boy this frustrates me a lot as a Hamcrest user)

Cobertura ā€“ a code coverage tool, alternate to Emma

Private methods shouldnā€™t be tested explicitly ā€“ you should be able to sufficiently test a class by its public facing API.

HTML 5 Intro

Of all the recent HTML 5 noise of late, and some pretty flashy webapps to be demoed from them, I got a little concerned that the HTML we know and love was going to turn into some RIA scripting beast.  Alas there is not much to be concerned with so far, this little tutorial starts with very small baby steps that people with limited CSS, HTML and JS exposure can appreciate.

Starting with a cool intro on the geolocation feature, then diverting to a javascript library to make code that tests for HTML 5 features more readable, its currently up to a modest part 3, talking about the new input types in the classic form element. 

Testing Presentations

Their has been a presentation I watched last year that absolutely changed my opinion on how I tested and how I designed.  It was one of those presentations that just made sense and I cant believe I havenā€™t blogged about it until now.

Integration Tests are a Scam by Joe Rainsberger

This was my favourite presentation from last year. It talks about writing the correct type of unit tests to get get fast results and reduce the need for slower integration tests that are generally slower are require a lot of maintenance. He makes a compelling argument about the number of tests in your system donā€™t improve the sense of security you get from your tests by the same amount. So he talks about what needs to be unit tested from the contract class and the opposite collaborator class and how doing so gives you a better picture of what tests you need to give you a sense of security with quick feedback. The blurb explains it better

Integration tests are a scam. Youā€™re probably writing 2-5% of the integration tests you need to test thoroughly. Youā€™re probably duplicating unit tests all over the place. Your integration tests probably duplicate each other all over the place. When an integration test fails, who knows whatā€™s broken? Learn the two-pronged attack that solves the problem: collaboration tests and contract tests.


TDD of Asynchronous Systems

This presentation by the author of a new book, ā€œgrowing object oriented software, guided by testsā€ Nat Pryce, which talks about testing at the integration/functional level and techniques to get around all the painful ā€˜flickering testsā€™ & ā€˜false positivesā€™ issues that occur when you have them. The examples talk about testing legacy systems, swing guiā€™s and JMS queues.

One of the key ideas is that one must find a point to synchronise on before executing the assertions and those assertions must wait (and retry if not true) until the state has changed or a timeout occurs (and the test then fails)

As a user of UISpec4j with its Assertions that have a timeout, and some perilious test code when someone innocently mixed junit assertions with a UI test, I could relate to this really well.

Seven Groovy usage patterns for Java developers

A colleague at my work recently added a Groovy console into one of our applications and it was this that reminded me of the ‘keyhole surgery’ pattern that I watched in a presentation last year by Groovy In Action author Dierk Konig last year…

Seven Groovy usage patterns for Java developers

Dierk Kƶnig, Canoo Engineering, Switzerland

Groovy is the new dynamic language for the Java platform that any Java?project can benefit from.?Learn when and how you can use Groovy as a “Super Glue”, heat up your Java?application with a “Melted Core”, alleviate pains with “Keyhole Surgery”,?adapt it to local needs with “Smart Configuration”, let it achieve?”Unlimited Openness”, enjoy subserving “House-Elf Scripts”, and provide?early feedback from a “Prototype”.

via Viddler.com – Ƙredev 2008 – Cool Languages – Seven Groovy usage patterns for Java developers – Uploaded by oredev.