Ignore Irrelevant Return Values
This is an installment in my Zero-Friction TDD series.
Sometimes, you don't care about the return value from a particular operation. The simplest example is if you want to check that creating a new instance of a specific type will throw an exception if supplied with wrong parameter values:
[ExpectedException(typeof(ArgumentNullException))]
[TestMethod]
public void CreateWithNullTextWillThrow()
{
// Fixture setup
int anonymousNumber = 8;
string nullText = null;
// Exercise system
new Plop(anonymousNumber, nullText);
// Verify outcome (expected exception)
// Teardown
}
In this example, even though the new operation is supposed to return a value, we don't care about it, since we only want to test that the correct exception type is being thrown. To save myself from having to stop and think about a variable name (even though in this case, I'd just have used sut), I prefer to not declare and assign the variable at all.
In general, I believe that APIs should follow the principle of Command-Query Separation, but sometimes it makes sense to break this rule. When you have an operation that both return a value and have side-effects, testing the side-effect via state-based testing doesn't require the return value.
Imaging that you have a method with this signature:
public object CommandQuery(int number)
Testing the side-effect may look like this:
[TestMethod]
public void CommandQueryWillUpdateNumberProperty()
{
// Fixture setup
int expectedNumber = 89;
int anonymousNumber = 11;
string anonymousText = "Anonymous text";
Plop sut = new Plop(anonymousNumber, anonymousText);
// Exercise system
sut.CommandQuery(expectedNumber);
// Verify outcome
Assert.AreEqual<int>(expectedNumber, sut.Number, "CommandQuery");
// Teardown
}
Notice that I've ignored the return value of the CommandQuery method.
Save yourself the time and effort it takes to declare and assign variables if you don't use them anyway.