我有这门课:
import 'package:flutter/material.dart';
class AgeText extends StatelessWidget {
final String dateOfBirth;
const AgeText({Key key, @required this.dateOfBirth}) : super(key: key);
@override
Widget build(BuildContext context) {
final age = _calculateAge();
return Text(age.toString());
}
int _calculateAge() {
final dateOfBirthDate = DateTime.parse(dateOfBirth);
final difference = DateTime.now().difference(dateOfBirthDate);
final age = difference.inDays / 365;
return age.floor();
}
}
我想测试一下,当一个出生日期传给它时,它会产生正确的年龄。在颤振中,最好的方法是什么?
解决方案
:对于感兴趣的人,下面是使用@g_¼nter z_¶chbauer的建议
clock
包裹。
我的小工具类:
import 'package:flutter/material.dart';
import 'package:clock/clock.dart';
class AgeText extends StatelessWidget {
final String dateOfBirth;
final Clock clock;
const AgeText({Key key, @required this.dateOfBirth, this.clock = const Clock()}) : super(key: key);
@override
Widget build(BuildContext context) {
final age = _calculateAge();
return Text(age.toString());
}
int _calculateAge() {
final dateOfBirthDate = DateTime.parse(dateOfBirth);
final difference = clock.now().difference(dateOfBirthDate);
final age = difference.inDays / 365;
return age.floor();
}
}
我的测试课:
import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/age.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets("shows age 30 when date of birth is 30 years ago", (WidgetTester tester) async {
final mockClock = Clock.fixed(DateTime(2000, 01, 01));
final testableWidget = MaterialApp(
home: AgeText(
dateOfBirth: "1970-01-01T00:00:00",
clock: mockClock,
),
);
await tester.pumpWidget(testableWidget);
expect(find.text("30"), findsOneWidget);
});
}