I am coding some unit tests for a MVC 5 internet application.
Should I hard code the expected value in the Assert
line of code, or calculate this value from the input values before they have changed.
Here is an example:
I have a function that subtracts the correct balance from an Account
object where the Account
object has a subscriptionCostPerDay
and an accountBalance
.
Here is the code:
account1.subscriptionCostPerDay = 0.99M;
account1.accountBalance = 10;
The function that I am testing calculates the subscriptionCostPerDay
and subtracts this from the accountBalance
. In the above example, the accountBalance
should be 9.01 after the function call.
Should the Assert
statement hard code the value of 9.01, or should the expected value be calculated from the original object values?
Here are examples of the two different types I am referring to above:
1.
Assert.AreEqual(9.01M, account1Balance, "Account 1 has correct account balance");
2.
decimal expectedAccount1Balance = account1.accountBalance - account1.subscriptionCostPerDay;
Assert.AreEqual(expectedAccount1Balance, account1Balance, "Account 1 has correct account balance");
Thanks in advance.
Unit Testing has two goals:
To achieve goal (1) your test is like proof-reading by a second person. You write the expected outcome of your test independently of the way you arrive at this result in your code.
Therefore it is very important, that account1Balance
is not calculated by the same formula as you use in your code. Exactly this formula may be buggy and writing the test is one way to find out.
Rule of thumb: "Expected values should not contain any logic".
There is a good Roy Osherove's blog post "Two different ways to create bad logic in unit tests" about that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With