作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试测试使用 FirebaseFirestore 的方法,但我无法模拟 FirebaseFirestore.instance 属性。
我正在关注这些例子:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(
Main(firebaseApp: Firebase.initializeApp()),
);
}
class Main extends StatelessWidget {
final Future<FirebaseApp> firebaseApp;
const Main({this.firebaseApp});
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: firebaseApp,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
final firestoreInstance = FirebaseFirestore.instanceFor(
app: snapshot.data,
);
return MyWidget();
}
return CircularProgressIndicator();
},
);
}
}
但是当我运行下面的测试时,我收到了消息:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class MockFirebaseApp extends Mock implements FirebaseApp {}
void main() {
FirebaseApp firebaseApp;
setUp(() async {
TestWidgetsFlutterBinding.ensureInitialized();
firebaseApp = MockFirebaseApp();
});
group('Main', () {
testWidgets('Loads my widget', (WidgetTester tester) async {
await tester.runAsync(() async {
await tester.pumpWidget(
Main(firebaseApp: Future.value(firebaseApp)),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
});
});
});
}
最佳答案
我有同样的问题。使用 this answer我找到了解决方案。
setupFirebaseAuthMocks();
在您的顶部 main
用于所有测试的功能。setUpAll
函数,调用 await Firebase.initializeApp();
(你也可以把它放在你的 main
函数下 setupFirebaseAuthMocks();
仍然有效)。import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_test/flutter_test.dart';
import '../lib/authentication/your_auth_using_firebase.dart';
import './mock.dart'; // from: https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_auth/firebase_auth/test/mock.dart
void main() {
// TestWidgetsFlutterBinding.ensureInitialized(); Gets called in setupFirebaseAuthMocks()
setupFirebaseAuthMocks();
setUpAll(() async {
await Firebase.initializeApp();
});
testWidgets('Your Test', (WidgetTester tester) async {
final YourFirebaseAuthClass authService = YourFirebaseAuthClass();
// Tests to write
});
}
关于firebase - 如何在 flutter 中模拟 FirebaseApp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63662031/
我是一名优秀的程序员,十分优秀!