Wasn't sure how to phrase that title, sorry!
I've just come across this in our code base, and was wondering what the consensus was about how to unit test it:
C# (-ish, sorry, this is paraphrased from memory)
class DateCalculator
{
public static DateTime CalculateLeadTime(DateTime deliveryDate)
{
//return the result of some determinate calculation involving deliveryDate
}
}
//New example
class OrderController
{
public ActionResult GetLeadTime(WidgetOrder order)
{
var leadTime = DateCalculator.CalculateLeadTime(order.GetDeliveryDate() );
return Json(leadTime.Value.Date.ToString("dd/MM/yyyy") );
}
}
//Old, incorrect example
class OrderService
{
public DateTime GetLeadTime(WidgetOrder order)
{
return DateCalculator.CalculateLeadTime(order.GetDeliveryDate() );
}
}
We've then got two unit tests, one to verify that CalculateLeadTime works (this is very easy, you can put in several test values and predict what comes out), and one that GetLeadtime works (still easy, but...). My question is: what would you test here, and where?
It makes sense to me to test CalculateLeadTime in isolation, because it could be a complicated calculation, and it's already a nice small predictable unit. But would you then go on to test some of the same stuff (maybe a single representative input and output?) in your GetLeadTime method? Or would you simply test that any DateTime value is returned, and assume that the calculation is correct because you're testing that somewhere else? Or would you not test the Calculate method on its own, because you know that you're going to test it when you use it, and you don't like the duplication?
EDIT: to muddy the waters a bit, I can see the code now, and rather than a Service, the calling class is an MVC Controller, and the Action under scrutiny is an AJAX method so returns the result of the calculation wrapped in JSON. The current test verifies that JSON is returned, but not the contents of it. Does this change anything?