问题
How can we make an acceptance/integration test on a feature that depends on date something happens?
For simplicity, let's assume this feature: we monitor a folder, and add items to a ListView corresponding to the received file. The colour of the listview item will depend on the date it is received. Say, if it's received on sunday, the colour is red, monday, it's blue, etc.
How can we make an test code on this feature without needing a week to run? Should the test code modify system date (But I'm afraid this will cause weirdness in the testing framework and report)? For information, the application is a .net and the developer uses DateTime.Now to get the receive time.
Note that this is not a unit test, this is an acceptance test that mimics the user interaction.
回答1:
- You will have to use a Fake Framework that can stub what DateTime.Now returns without needing an interface. Like TypeMock
- Otherwise, you could create your own Date object that you have more control over faking (this is less desirable in this case as it is only being done to test your code)
- Otherwise, you could create a class that has a GetCurrentDate method that you can stub. In your prod implementation you can use DateTime.Now, but in your test, you can stub it out so that it returns whatever date you want. This is probably the best solution IMO
However, this will not test the full, true implementation and is more of a unit test. If you are indeed talking about end to end integration testing, then yes, you will need to modify the system time.
回答2:
Change your time to just before the event.
回答3:
What you need is some way to "mock" the DateTime interface -- that is, to make DateTime return predetermined values rather than the current time. The process of "injecting" a mock class to replace an existing one is known as "dependency injection" (DI), and a number of frameworks for performing DI are discussed at:
Which .NET Dependency Injection frameworks are worth looking into?
回答4:
If it's acceptance testing requiring user interaction, you're best bet would be to change the system time.
If it's unit testing, you need to pass in the dependency (DateTime) into the method to be tested.
来源:https://stackoverflow.com/questions/9731526/how-to-test-a-feature-that-depends-on-date-events-happen