I've just written a unit test for this function, which loops through a collection of dates and sets properties equal to true or false depending on whether they're before or after a given comparison date:
public void CheckHistory(int months)
{
var endDate = DateTime.Today.AddMonths(months);
Dictionary<Order, bool> orders = new Dictionary<Order, bool>();
foreach (var kvp in this.Orders)
{
if (kvp.Key.Date >= endDate)
{
orders.Add(kvp.Key, true);
}
else
{
orders.Add(kvp.Key, false);
}
}
this.OrderHistories = orders;
}
So here's the test I wrote:
public void Assert_CheckHistory_SelectsCorrectDates()
{
MyViewModel vm = GetVmWithMockRepository();
vm.OrderHistories = new Dictionary<OrderHistory, bool>();
OrderHistory ohOld = new OrderHistory();
ohOld.MailingDate = DateTime.Today.AddMonths(-12);
vm.OrderHistories.Add(ohOld, false);
OrderHistory ohNew = new OrderHistory();
ohNew.MailingDate = DateTime.Today.AddMonths(-3);
vm.OrderHistories.Add(ohNew, false);
vm.CheckOrderHist(-6);
int selectedOrders = vm.OrderHistories.Where(o => o.Value == true).Count();
Assert.AreEqual(1, selectedOrders, "Unexpected number of selected Order Histories");
}
Nothing wrong there. Test passes and all is good with the world.
However, I'm haunted by a nagging feeling that I'm not actually testing anything useful, and am just writing tests for the sake out it.
I get this a lot. A creeping paranoia that the tests I'm writing are incomplete in the sense that while they cover the lines of code in the target function, they don't really trap any likely problems and are therefore just a maintenance overhead.
Is that sample test worthwhile? Is even a badly-designed test worth worthwhile over no test at all? And most of all are there any principles to help programmers identify whether a test is useful or not, or to guide them in constructing useful tests in the future?
To be clear, I'm adding tests to an existing application. Going test-first in true TDD style isn't possible.