If This is Inversion of Control, Then I Like It

2008.02.06 06:33

I’ve seen the terms Inversion of Control and Dependency Injection used interchangeably, but I don’t think that they are really the same thing.

I was working on some integration tests for a Job system. Each test:

  1. Created a JobGroup.
  2. Did some things to the JobGroup.
  3. Destroyed the JobGroup in a finally block.

I got a bad taste in my mouth, like I was writing too much code. So here’s what I did:

(NOTE: My integration tests are completely self-rolled, so I do not currently have the luxury of TestNG or JUnit setUp/tearDown methods. I haven’t found a way to integrate OSGi’s classloading and declarative service activation with those libraries. That’s another discussion.)

I defined an abstract class that all tests will provide an instance of:

/**
 * Defines a test to be run within a JobGroup.
 */
private abstract class JobTest {

    String name;

    JobTest(String name) {
        this.name = name;
    }

    abstract void run(JobGroup group);

}

I defined a method that accepts the JobTest instance. It creates/destroys the JobGroup before/after the test runs.

/**
 * Creates a JobGroup, passes it to test, destroys JobGroup.
 */
private void runTest(JobTest t) {
    final JobGroup group = this.jobService.createJobGroup(t.name);
    try {
        t.run(group);
    } finally {
        group.destroy();
    }
}

Here’s an example test:

@Test
public void submitExecutableJob() {
    runTest(new JobTest("submitExecutableJob") {
        @Override
         void run(JobGroup group) {
            final WaitingJob job = new WaitingJob("default");
            group.submit(job);

            // verify that job hasn't started
            verify(!job.started, "Job should not have started.");

            // enable job
            job.enable();

            // verify that job finishes
            job.awaitFinish(1, TimeUnit.SECONDS);

            verify(job.finished, "Job did not finish.");
        }
    });
}

Comments? (moderated as hell)

allowed HTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>