我想编写一个测试用例,以确保在我正在开发的 Flutter 应用程序中使用
toLocal
函数,因为忘记了这是一个反复出现的问题。 注意:我不是询问如何测试该功能,我确信 Dart 开发人员在这方面做得很好。我想编写一个测试用例来确保调用该函数。
数字,应该像这样简单:
// Function I want to test
int getLocalHour(DateTime dateTime) => dateTime.toLocal().hour;
void main() {
test('getLocalHour uses local time', () {
final testedTime = DateTime.utc(2022, 9, 20, 12);
expect(getLocalHour(testedTime), 14);
});
}
现在您可能会说“等等,世界标准时间 12 点在我的时区不是下午 2 点”,您可能是对的!这就是我遇到的问题;我找不到可靠的方法来设置时区以用于
toLocal
以获得可重现的结果。在 CEST 中,这个测试在我的笔记本电脑上运行良好,在冬天,它会失败。在 CI 中,它全年都会失败,因为它运行在配置为使用 UTC 时间的服务器上。
有没有办法让
toLocal
产生预定的输出,这样我就可以确保它在我需要调用的地方被调用?
您可以在测试中自行转换为当地时间,并与该值进行比较。
void main() {
test('getLocalHour uses local time', () {
final testedTime = DateTime.utc(2022, 9, 20, 12);
final testedLocalTime = testedTime.toLocal();
expect(getLocalHour(testedTime), testedLocalTime.hour);
});
}
如果您在 GMT 中运行测试并且忘记调用
toLocal
,则会意外通过。对此没什么可做的。
团队合作让梦想成真!每个人都提出了很好的评论和问题。这是一个有效的代码片段。是否可以优化请评论。
使用时区包,我们首先初始化时区,通过
getLocation
将时区位置设置为柏林(只是一个示例),然后setLocalLocation
以便toLocal()
正确响应。
要更改的另一部分是使用
TZDateTime.utc()
表示测试时间。现在一切都已正确模拟并且测试通过。
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;
int getLocalHour(DateTime dateTime) => dateTime.toLocal().hour;
void main() {
tz.initializeTimeZones();
final berlin = tz.getLocation('Europe/Berlin');
tz.setLocalLocation(berlin);
test('getLocalHour uses local time', () {
final testedTime = tz.TZDateTime.utc(2022, 9, 20, 12);
expect(getLocalHour(testedTime), 14);
});
}