Now let's refactor the unit tests
we have written. The first thing we always do before refactoring is run the unit tests to be sure we start at 100%.
In this case we are going to be working with the unit tests themselves. We are using our code now to verify the
unit tests were refactored correctly instead of the other way around. |
|
package simulator.r12.unittest;
import unittest.framework.*;
import simulator.r12.*;
class SwitchTest extends Test implements SimulationInterface
{protected int onMessageSent, offMessageSent,
otherMessageSent;
private Thread simulation;
static final int BoilerSwitch =
0x1000;
static final int ReliefValveSwitch
= 0x2000;
public void setUp()
{onMessageSent = 0;
offMessageSent = 0;
otherMessageSent = 0;
PIA.register = 0x0000;
PIA.setInputs(0x003F);
startSimulator();}
public void runTest(int theSwitch)
{testSwitchOn(theSwitch);
testSwitchOff();}
public void tearDown()
{stopSimulator();}
private testSwitchOn(int theSwitch)
{PIA.write(theSwitch);
pauseOneQuarterSecond();
should(onMessageSent == 1, "Got
on message " + onMessageSent + " instead of once");
should(offMessageSent == 0, "Got
an off message");}
private testSwitchOff()
{PIA.write(0x0000);
pauseOneQuarterSecond();
should(onMessageSent == 1, "Got
an on message instead");
should(offMessageSent == 1, "Got
off message " + offMessageSent + " instead of once");
should(otherMessageSent == 0, "Got
some other message");}
public void boilerOff()
{otherMessageSent++;}
public void boilerOn()
{otherMessageSent++;}
public void reliefValveOff()
{otherMessageSent++;}
public void reliefValveOn()
{otherMessageSent++;}
private void startSimulator()
{simulation = new Simulator(this);
simulation.start();}
private void stopSimulator()
{simulation.stop();
simulation = null;}
private void pauseOneQuarterSecond()
{try
{Thread.sleep(250);}
catch (InterruptedException exception)
{};};}
|
What we did to create this super
class is to find everything that was in common between the two classes we already had and create a generic version.
With this super class recreating our two tests is easy. |
|
package simulator.r12.unittest;
class TestBoiler extends SwitchTest
{public void runTest()
{runTest(BoilerSwitch);}
public void boilerOff()
{offMessageSent++;}
public void boilerOn()
{onMessageSent++;};}
package simulator.r12.unittest;
class TestReliefValve extends SwitchTest
{public void runTest()
{runTest(ReliefValveSwitch);}
public void reliefValveOff()
{offMessageSent++;}
public void reliefValveOn()
{onMessageSent++;};}
|
Run the new unit tests and they
pass. We can add the third simply now. But before we do that let's refactor our simulator
class first. There is a lot of code that looks just alike and I think it could be simpler.  |
|