Avoid magic values

Like in production code, the way you are using and naming variables in unit tests is important. A magic value is a value that you use in your test without providing any context about it.

This may confuse the other developers as they will wonder why a certain value was used, rather than focusing on the test itself.

When writing unit tests, you should try to express intent as much as possible. Instead of using magic strings, a good approach is to use constants.

Example

This unit test looks simple, but someone who has not good understanding the production code cannot easily know why the values 0.5 and 10.00 were used.

@Test
void calculateShippingFee_Should_Return_Small_Box_Fee_When_Weight_Lower_Than_1Gk(){

double fee = ShippingCalculator.calculateShippingFee(0.5);

assertEquals(10.00, fee);
}

Improved example

To fix this, you can use constants and name them in a convenient manner. Don’t be afraid of using long constant names to express the intent of your code.

@Test
void calculateShippingFee_Should_Return_Small_Box_Fee_When_Weight_Lower_Than_1Gk(){

final double LESS_THAN_1KG_WEIGHT = 0.5;
final double BASE_FEE = 0.5;

double fee = ShippingCalculator.calculateShippingFee(WEIGHT);

assertEquals(BASE_FEE, fee);
}

Leave a Reply

Your email address will not be published. Required fields are marked *