Controlling time in a unit test allows you to test code that depends on the passage of time like Timer or time comparisons. Dart makes it easy as long as you use the Clock package in code that gets dates instead of using DateTime directly. For any code using Clock time can be controlled through the FakeAsync package. Example Time Test Two key things to note in this example test. First that the test is wrapped in the fakeAsync method. Second that the first time clock is used is inside the fakeAsync wrapper. That’s important, if you access the clock [Read on…]
Tag: dart
Flutter Null Safety Unit Tests: Late for Tests
Dart added the late keyword as part of their null safety release and it is very useful, particularly for testing. As a quick review null safety means telling the compiler that some variables will never be null. Any variable declared without a question mark following the type declaration is null safe. So String name is null safe while String? name can be null. Given that the question mark is new syntax all code written before null safety was introduced now declares all variables as cannot be null. The new late keyword tells the compiler that although a variable is not [Read on…]
Null Safety firstWhere
The change to null safety in Dart is a good thing, however a common pattern I used firstWhere for got broken. The pattern is to search a collection and return null if the search returns nothing. The short answer is that you should use firstWhereOrNull instead in this case. Example of the Issue Before the null safe version of Dart the code would look like this: The naive conversion to null safety would be: But this conversion will show a warning that the test if ( null == val ) is not required because the value can’t be null. What’s [Read on…]
DST Dart and DateTime & How to Unit Test
Like all programmers I have a pretty long held grudge against daylight savings time, leap years, time zones, and just generally anything to do with dates and times. The ways in which date complexity have hurt over the years are many and varied. This year’s pain provided a good opportunity to use the excellent unit test support for time in Dart. This post is a tiny bit about date calculations and mostly about how to get control over dates in tests. What Went Wrong This Year This is the history and context part of the post. If you just want [Read on…]
Markdown Parsing in Dart
Markdown content has become pretty ubiquitous and along with that comes the requirement to parse it into its constituent parts. Sometimes it’s useful to know what links it contains, or to count the headings, etc. Writing parsers is super fun in comp sci class, and not too bad with something like Antlr, but when someone else has already done the work, so much the better. Dart has a very capable Markdown parser that is only missing a little bit of documentation to make it fit this more general requirement. This post fills in that bit of documentation. The Basics Markdown [Read on…]