What Is A Dummy?
As conscientious software developers, we unit test our code. Sometimes, we must provide parameter values to functions when writing unit tests even though we won’t use those parameter values. In these cases, we may supply dummy values.
Let’s look at an example.
Below is a unit test for a high-level business logic workflow class, ChangeOrderUseCase
, that enables us to change an existing customer order:
[Fact] public void Given_No_OrderChange_When_Call_Change_Then_Throw_MissingOrderChange_Exception() { var useCase = new ChangeOrderUseCase(null); Action change = () => { useCase.Change(null); }; change.Should().Throw<MissingOrderChange>(); }
The unit test verifies that when we call the Change()
method with a null
OrderChange
argument, then a MissingOrderChange
exception is thrown.
Let’s take a look at the definition for ChangeOrderUseCase
class and its Change()
method:
public class ChangeOrderUseCase { private IOrderRepository Repository { get; set; } public ChangeOrderUseCase(IOrderRepository repository) { Repository = repository; } public void Change(OrderChange change) { if (change == null) throw new MissingOrderChange(); var order = Repository.GetOrder(change.OrderNumber); order.ApplyChange(change); Repository.SaveOrder(order); } }
When we pass Change()
a null
argument, the method throws a MissingOrderChange
exception, precisely as the test said it should. Of course, throwing the exception means that we immediately exit the method and therefore Repository.GetOrder()
is never called. This unit test does not require a valid OrderRepository—we can use a dummy value instead. Would a null
work?
Let’s take another look at the unit test:
[Fact] public void Given_No_OrderChange_When_Call_Change_Then_Throw_MissingOrderChange_Exception() { var useCase = new ChangeOrderUseCase(null); Action change = () => { useCase.Change(null); }; change.Should().Throw<MissingOrderChange>(); }
Notice how we are passing a null
value into the ChangeOrderUseCase
constructor. That null
is the dummy value getting assigned into the Repository
, which we’ll never call for this unit test. Yes, a null works fine here.
In unit testing, dummies are values for variables and references that we don’t use yet must supply.
Leave a Reply
Want to join the discussion?Feel free to contribute!