![]() ![]() Once this has been done it easily be tested but how does it run? We need to make sure it has been registered with our DI container. Once the concrete class has been defined we can now update the HomeController to take in a dependency of IClock. Public DateTimeOffset UtcNow => DateTimeOffset.UtcNow public interface IClockĪnd then create the default implementation. I've seen it called IClock and IDateTimeOffSet so it's completely down to personal preference but the concept is the same. IClock interfaceīy using an interface to define the properties you want. So how do we resolve this to make sure that we use a well known starting point for testing purposes but at run time rely on the correct value? Abstract it away. Now this in itself is clear however can potential cause issues with testing. Return (1).Hour Īnd this will return next hour based on Utc. ![]() The Service Under Test (SUT)įor this example the sut will be a very basic MVC controller which outputs next hour: public class HomeController ![]() The same principles can be applied to full framework using a DI container. Once we've done that we can unit test for different values and make our code more robust.Īll the examples are using the preview of aspnetcore 2.1 however none of the code is 2.1 specific so will work in current 2.x aspnetcore. So how do we solve this problem? We need to remove the direct reliance on DateTime and DateTimeOffSet static properties. Most of the time this is due to developers using DateTime.UtcNow (or variant) inside the code being tested but the tests expecting specific values. Over the years I have experienced a number of unit tests passing without issue on a Friday but Monday morning without any changes fail. Now most of the time these items won't make a difference but if you write code which is datetime dependent or financial software which has tax year calculations in then it maybe time for some pain. It's also coming up to the time of year, in the UK, that the new tax year starts.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |