Testing the Pre-Flight Sequence
In my blog entry Just Write A Test, I promised to write about how to test a void function. Let's consider a scenario where I need to do just that.
I’ve just taken ownership of the sprint backlog item “Automate Pre-Flight Sequence”. I clarified a few things in the acceptance criteria with my team’s Product Owner, took some time to whiteboard a design with my team, and finally sat down with my coffee to write my first test prior to implementation. I look at my notes and see that the first step of the pre-flight sequence is to press the green button, so let’s take a look at how to structure my test by starting with my Arrange step of the Arrange-Act-Assert paradigm.
[TestInitialize]
public void Arrange()
{
_bridgeConsole = new MockBridgeConsole();
_command = new PreFlightSequenceCommand(_bridgeConsole);
}
In my Arrange()
method annotated with the TestInitialize
attribute, I have instantiated a mocked version of my BridgeConsole
. That is, I have a test-only implementation of the BridgeConsole
’s interface and all it does is track a collaborator component’s interactions with it. I then constructor inject the MockBridgeConsole
instance into my class under test, which is the PreFlightSequenceCommand
. Now I’m ready to write a test!
[TestMethod]
public void CallsPressGreenButton()
{
_command.Execute();
Assert.AreEqual(1, _bridgeConsole.PressGreenButton_CallCount);
}
I name my method to clearly express its intent, and then perform my Act step by calling the method under test, which is _command.Execute()
. That just leaves my Assert step. Since my MockBridgeConsole
exposes me ways to observe method call counts, I simply write an assertion that I've called the PressGreenButton()
method once.
Now I can create my class with its constructor to satisfy my compiler, then call the aforementioned PressGreenButton()
method to make my test pass. I don't have any black box tests because I have to know how the PreFlightSequenceCommand
works in order to test it at all, so I skipped straight to the sense tests that assert behavior in the body of my method.
There are other ways to test void methods depending on what they do. You can encounter more complex scenarios where the body of the method mutates the program state in other ways, such as manipulating database entity objects. If you would like me to tackle a specific scenario, hit me up in the comments!
Photo by Dan Lohmar on Unsplash