Testing commands

Strongback’s command framework was designed to make testing easy. For some stateless command classes that just provide an execute() method, it’s easy to test the basic logic with a simple unit test. We saw an example of this in an earlier section:

public class OpenClawTest {
    @Test
    public void shouldRetractSolenoidWhenSolenoidIsInitiallyExtended() {
        MockSolenoid solenoid = Mock.instantaneousSolenoid().extend();
        OpenClaw command = new OpenClaw(solenoid);
        assertThat(command.execute()).isTrue();
        assertThat(solenoid.isRetracted()).isTrue();
        assertThat(solenoid.isExtended()).isFalse();
    }
    @Test
    public void shouldRetractSolenoidWhenSolenoidIsAlreadyRetracted() {
        MockSolenoid solenoid = Mock.instantaneousSolenoid().retract();
        OpenClaw command = new OpenClaw(solenoid);
        assertThat(command.execute()).isTrue();
        assertThat(solenoid.isRetracted()).isTrue();
        assertThat(solenoid.isExtended()).isFalse();
    }
}

Other command subclasses might be more difficult to test this way. For example, if the command class has state or relies upon the initialize(), interrupted(), and/or end() methods, then these simple unit tests need to replicate the proper lifecycle operations on the command. To make this easier, Strongback’s testing library (which your tests can depend upon but which you would not deploy to your robot) includes a CommandTest class that lets your test step through the various lifecycle states.

Here’s an example unit test that uses CommandTester to test the command created by Command.pause(…​). It uses the time facility within CommandTester to manipulate the clock (independently of the JVM’s clock).

public class PauseTest {
    @Test
    public void shouldFinishAfterTime() {
        Command command = Command.pause(5,TimeUnit.SECONDS);
        CommandTester runner = new CommandTester(command);
        assertThat(command.step(1000)).isEqualTo(false);
        assertThat(command.step(5000)).isEqualTo(false);
        assertThat(command.step(5010)).isEqualTo(true);
    }
}

results matching ""

    No results matching ""