Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected values in unit tests

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.

like image 978
user3736648 Avatar asked Feb 02 '15 06:02

user3736648


2 Answers

Unit Testing has two goals:

  1. Find bugs in your code when the test does not work the first time
  2. Make sure your code stays correct for times to come

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.

like image 53
DrKoch Avatar answered Oct 20 '22 20:10

DrKoch


Rule of thumb: "Expected values should not contain any logic".

  1. If there's a bug in the code, and we use the same logic to calculate the expected value in the test, we are replicating the bug.
  2. The logic calculating the expected value can be flawed, thus we end up having the bug in the test code.
  3. Having readability in mind, it's easier to perceive hard-coded value.

There is a good Roy Osherove's blog post "Two different ways to create bad logic in unit tests" about that

like image 23
buxter Avatar answered Oct 20 '22 20:10

buxter