When testing the application, sometimes you don't want the actual current date to be used. You'll want to use a specific date. If you hardcode a call to get the current date, you won't be able to change it for testing. Using an object like this allows you to replace it in your testing environment with one that provides any date you want.
Is it not possible to just mock the Date function? Does swift have prohibitions on mocking builtins? I know the response might be “but what if they change the behavior of Date()?” - realistically that doesn’t happen very frequently, if ever
It's not a function. Well technically it's the date's init function but no it is not possible to mock it. Also Date is a struct not a subclass so you can't just substitute it with a subclass.
I know literally nothing about swift but no, most languages don't prohibit you from mocking builtins. They do, however, usually prevent you from replacing them. The idea is that you want to use dependency injection or perhaps pass a CurrentDateRetrievingProtocol as an argument to the method/class/whatever. That way you can give a mocked version of that object to the consumer. There's not really another way to do it, i.e. literally replacing the Date function. Generally, that is. Even when this is possible, it's generally not advisable.
Say for example, you have code that checks the time of day and prints "Morning", "Afternoon" or "Night".
If you write a test case to check that it outputs night after 19:00, but your code is using something like new Date() (or Date.now(), etc.. depending on lang).. then, that test case would fail if you run it in the morning or afternoon and succeed when you run it on the nightly build which is a very bad idea.
So you abstract the functionality of getting the current date. So, when you run the real code, you can provide an implementation that might use date(), but for testing, you can have a mock object that returns the value you need for testing (e.g. something after 19:00).
System time is infrastructure, like logging, db access, or file system access. You want to write wrapper interfaces for all of those to make sure your domain logic is not hard coded to w/e system your running on. This means it doesn't matter if you're running on a user pc, on-prem server, cloud functions or unit testing on a build server. As long as you provide an implementation for that hardware, your code will run and work properly.
It’s not the same thing. The caller should be able to get the date whenever they want it. Imagine if this were used to profile a piece of code with start/stop calls.
By making it an argument you're just moving the problem about, while making your code less readable. You still need the calling class to get date somehow, and adding Date() there is just as bad.
System time is infrastructure, much like logging, db access or file system access, and should be abstracted away to allow for testing and mocking. DI and testable code 101.
And it's worth noting that this can be important for multiple types of tests. Both unit tests, or stuff like back-testing trading strategies (where you run trading algorithms against historical quote and trade data to see if your algos would have made or lost money during different market conditions).
Both can be critically important. There's a lot of value in abstracting away the way you get current date/time info to facilitate that testing.
have fun debugging date related issues in your tests... I swear most posts on reddit about programming jokes or bad code just haven't written any professional code
calling Date() does not follow the dependency inversion principle, imagine you have some method you wanna test that deletes all entries that are 2 weeks old, and now imagine writing units tests for that.
either your tests take 2 fucking weeks to complete, or you correctly do dependency injection
This is something I picked up on my own as I started writing more code.
"hmmm... It sucks when I need to go through all this code to find that one "14" for 14 days ago. What if I need to change that? Or what if I need to test different permutations?"
I'm getting used to using functions more often too. As others have said, it's way easier to adjust a block of code in a function and test the function separately. Especially in literally any situation where you do the same thing more than once and need the output to always remain consistent.
To be honest, this example seemed overly complicated to me too until people started mentioning why anyone would do it.
And now that I think about it, I've done something very similar when I needed the date to always be formatted in a certain way. It was literally one line of code, and the function was probably also called getCurrentDate
You should generally shim your business logic from all other factors such as DB concerns, file references, protocol formats, and so on including the framework itself. It takes work, sure, but keeps your concerns pure and makes things very maintainable and testable. It has a great side effect of also making it portable.
it looks pretty stupid, but it's useful for testing. I use a TimeProvider interface and class in my Unity test code. something like
public interface ITimeProvider
{
int TimeInSeconds { get; }
}
public class TimeProvider : ITimeProvider
{
public int TimeInSeconds => Time.time;
}
public class TestTimeProvider : ITimeProvider
{
public int TimeInSeconds { get; set; }
}
this code allows me to use the time elapsed within the scene for production code and use a specific point in time for testing. otherwise, if I have a timed event for let's say one minute, I would have to wait one minute, every time a test uses this timed event
It really depends on the language. In C# (and others) you can’t replace the DateTime objects for testing (like at all, well you can in Visual Studio Ultimate but I have never worked anywhere that sprang for it) so you wrap it, inject the wrapper into your logic class, then when testing can use a mocking framework to mock the wrapper output a known time.
Here is a good 5 minute read why you should exactly to this instead of calling Date() directly: https://dev.to/pnieweglowski/why-using-datetime-now-directly-is-a-bad-idea-1gob. No matter the framework. But I would like to add an "it depends" statement of my own. It depends on your project size and architecture. I wouldn't do that for a simple PoC or Prototype nor for a small application which isn't mission critical.
I associate the IoC pattern with runtime dependency injection, like we see in the Spring framework. That has a lot of meaningful use cases but there are cases (like ultra low latency systems) where they're not appropriate.
But if we're using IoC to mean the general practice of abstracting the instantiation of the concrete implementations of key abstract classes or interfaces based on config, environment, or command line arguments, then I agree it's almost universally useful.
179
u/kbielefe Sep 27 '21
I don't know swift, but in many languages something like this is the only way to mock out the date for tests.
121
u/Tvde1 Sep 27 '21
have fun debugging date related issues in your tests... I swear most posts on reddit about programming jokes or bad code just haven't written any professional code
61
u/Almamu Sep 27 '21
This is the proper way of doing it imo. Easily testable and easy to replace the logic of how current dates are constructed if ever needed
34
u/cramt Sep 27 '21
calling Date() does not follow the dependency inversion principle, imagine you have some method you wanna test that deletes all entries that are 2 weeks old, and now imagine writing units tests for that.
either your tests take 2 fucking weeks to complete, or you correctly do dependency injection
15
u/[deleted] Sep 27 '21
You should generally shim your business logic from all other factors such as DB concerns, file references, protocol formats, and so on including the framework itself. It takes work, sure, but keeps your concerns pure and makes things very maintainable and testable. It has a great side effect of also making it portable.
11
u/g_hi3 Sep 27 '21
it looks pretty stupid, but it's useful for testing. I use a TimeProvider interface and class in my Unity test code. something like
this code allows me to use the time elapsed within the scene for production code and use a specific point in time for testing. otherwise, if I have a timed event for let's say one minute, I would have to wait one minute, every time a test uses this timed event
8
u/ce-walalang Sep 27 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
4
u/AnuragMishra Sep 28 '21 edited Sep 28 '21
Dependency inversion is a good practice but OOP also celebrates excessive ceremony. I would replace this with a closure
3
u/Rrrrry123 Sep 27 '21
Is a protocol in this language like an abstract class?
3
u/matsre1994 Sep 28 '21
This is encapsulation. This is NOT bad code. It allows for testing and mocking of value types that usually is hard to test/fake.
1
u/Cotspheer Sep 27 '21
Here is a good 5 minute read why you should exactly to this instead of calling Date() directly: https://dev.to/pnieweglowski/why-using-datetime-now-directly-is-a-bad-idea-1gob. No matter the framework. But I would like to add an "it depends" statement of my own. It depends on your project size and architecture. I wouldn't do that for a simple PoC or Prototype nor for a small application which isn't mission critical.
1
u/ExistedDim4 Sep 30 '21
Java moment
1
u/ekolis Sep 27 '21
That protocol thing looks like a C# interface. I like the name "protocol" better.
0
u/[deleted] Sep 27 '21
[deleted] — view deleted comment
0
u/[deleted] Sep 27 '21
[deleted] — view deleted comment
15
u/[deleted] Sep 27 '21
[removed] — view removed comment