Last Updated: February 25, 2016
·
263
· hoffoo

Prototype JavaEE Beans without mocking

I do not write integration tests for database code (DAOs) because its a waste of time. You are going to wire up some data that the code is supposed to work with, and then test against that. When the schema changes, and you are running with that wrong data, your test becomes meaningless.

This is where integration tests come in - the point is that you are running against a real DB (hopefully not a production DB..) and can test everything out for real. But setting this up is a pain in the ass, not to mention that if you are actually trying to prototype something, or just try out some new DAO method, its much more convenient to run your code in a real environment.

First I write a class that will with @Startup on @PostConstruct. Then fire it up with a debugger and watch it go.

@Singleton
@Startup
public class SomeSandbox {

    @EJB
    SomeBean b;

    @PostConstruct
    public void init() {

        // loop until the function is doing what I want
        boolean rerun = true;
        do {
            doSomething();
        } while(rerun);
        // unset rerun in the debugger and test the function out for real
    }

    private void doSomething() {
        // do something with bean
    }
}

What this lets me do is set a breakpoint at doSomething() and tweak the method until it does what I want. Then in my debugger I set rerun to false the application continues with its day giving me the chance to try out my new code for real. When I am done I delete my sandbox code and write a solid test that is as future proof as possible.

Its simple, effective, and lets me try code in the ecosystem that its going to run in, rather than mocking something entirely.

The downside to this method is that you still have to write your integration test afterwards, but I prefer this method anyway. I am not a big fan of "write a test and watch it fail until it passes" especially when doing something against a database.