Should you use a magic number in unit tests?


unit-test Should you use a magic number in unit tests? c # code review unit test

unit-test

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:

1
2
3
4
5
6
[Test]
public void GivenSomething_WhenDestinationIndexSetTo5000_ThenIsSomethingTrue()
{
  var layout = new Layout() { DestinationFloorIndex = 5000};
  Assert.That(layout.IsSomething, Is.True);
}
[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?

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
251 words
Last Post: SteemIt: Your comments will be hidden if you are muted
Next Post: SteemSQL Tutorial: How to Avoid SQL Injection?

The Permanent URL is: Should you use a magic number in unit tests?

Leave a Reply