Should you use a magic number in unit tests?

in #programming9 years ago (edited)

Magic numbers are not good, we want to avoid them as much as we can. However, there is one exception, as described in the following C# example:

[Test]
public void GivenSomething_WhenDestinationIndexSetTo5000_ThenIsSomethingTrue()
{
  var layout = new Layout() { DestinationFloorIndex = 5000};
  Assert.That(layout.IsSomething, Is.True);
}

This is some code review that I came across today. Some engineers may not like the magic numbers even in the unit tests. But, I think it is ok in this case because:

What the author was trying to avoid here was writing a test that proves the const defined in Layout.ID is equal to itself by using the value specified. That way if someone changes the Const value then a least his/her test will fail forcing the developer who made the change to think twice before actually changing it. This is why the number is stated in the name of the test method.

What do you think?

Sort:  

a good program.and quality information

you shouldn't hard code variables, tests are a place where mess is more ok but generally its a bad idea and will cost you time and labor in the long run

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.089
BTC 61413.85
ETH 1701.65
USDT 1.00
SBD 0.38