Handling unit tests with a condition on the current time

女生的网名这么多〃 提交于 2019-11-30 11:31:04

Definitely mock out new Date().

Create a Clock interface with a getCurrentTime() method or something similar. That way you can have a FakeClock for testing and a SystemClock which uses System.currentTimeMillis() or whatever.

I've done this a number of times - it's worked extremely well. It's logical too - effectively you require a "current time service" so that should be injected like any other dependency.

I usually inject a date provider into the tested code. This also helps if you need to switch conventions or otherwise "fix" the time testing code.

Use dependency injection and inject a TimeProvider that provides a getExpiryDate() method.

If you feel the TimeProvider/Clock abstraction is too overboard perfectionist (which may very well be the case), consider this instead

Make getCurrentType protected virtual, then create a TestingProductionType decendant of the ProductionType that contains the code you posted. In that type, override the getCurrentType() method to return some deterministic result. In your unit test, create an instance of this TestingProductionType instead.

Viola, the dependency of current time is now removed from your unit tests. The only production code that is now not unit tested is a method with a single line returning new Date(). I could live with that.

If you can check out Mole at http://research.microsoft.com/en-us/projects/pex/ Moles allows to replace any .NET method with a delegate Just use it to replace Date and have it return what ever you need. Then you don't need to do anything crazy.

-Raul

All three approaches are possible:

  1. don't test: lazy man's way
  2. use a license that won't expire for ages until you've left the job: cover my ass way
  3. use a mock for the current date, such as a TimeProvider: the perfectionist way

I'd go for a comprimise: I'd add the current date as a parameter to the isExpired method, and the isValid method. For your live production code, add a simple isValid() no-arg override that calls isValid(new Date()). Your test code uses the version that takes the current date as the parameter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!