Firebase身份验证单元测试错误没有Firebase应用程序

2023-12-02

我正在尝试测试我的firebase auth方法。身份验证方法有登录、注销、注册等。 这是我想要执行单元测试的方法。

我收到错误No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

我尝试初始化Firebase.initializeApp测试中main方法它也不起作用。

 class MockUserRepository extends Mock implements AuthService {
  final MockFirebaseAuth auth;
  MockUserRepository({this.auth});
 }
 class MockFirebaseAuth extends Mock implements FirebaseAuth{}
 class MockFirebaseUser extends Mock implements FirebaseUser{}
 class MockFirebase extends Mock implements Firebase{}
 void main() {
   MockFirebase firebase=MockFirebase();
   MockFirebaseAuth _auth = MockFirebaseAuth();
   BehaviorSubject<MockFirebaseUser> _user = BehaviorSubject<MockFirebaseUser>();
   when(_auth.onAuthStateChanged).thenAnswer((_){
      return _user;
     });
   AuthService _repo = AuthService.instance(auth: _auth);
   group('user repository test', (){
       when(_auth.signInWithEmailAndPassword(email: "email",password: "password")).thenAnswer((_)async{
  _user.add(MockFirebaseUser());
});
when(_auth.signInWithEmailAndPassword(email: "mail",password: "pass")).thenThrow((){
  return null;
});
test("sign in with email and password", () async {
  var signedIn = await _repo.onLogin(email:"[email protected]",password: "123456");
  expect(signedIn, isNotNull);
  expect(_repo.status, Status.Authenticated);
});

test("sing in fails with incorrect email and password",() async {
  var signedIn = await _repo.onLogin(email:"[email protected]",password: "666666");
  expect(signedIn, false);
  expect(_repo.status, Status.Unauthenticated);
});

test('sign out', ()async{
  await _repo.signout();
  expect(_repo.status, Status.Unauthenticated);
 });
});
} 

认证服务类

    enum Status { Uninitialized, Authenticated, Authenticating, 
    Unauthenticated }

   class AuthService with ChangeNotifier {
     FirebaseAuth auth = FirebaseAuth.instance;
     FirebaseUser _user;

    FirebaseUser get user => _user;

    set user(FirebaseUser value) {
      _user = value;
    }

    Status _status = Status.Uninitialized;

    Future<User> getCurrentUser() async {
      User currentUser;
      await FirebaseAuth.instance.authStateChanges().listen((User user) {
      currentUser = user;
      });
      return currentUser;
     }
    AuthService();
    AuthService.instance({this.auth}) {
       //    auth.onAuthStateChanged.listen((user) {
      //      onAuthStateChanged(user);
      //    });
      }

     Future<void> signout() async {
     await auth.signOut();
       }

     Future<User> createAccount({String email, String password}) async {
        try {
           UserCredential userCredential = await 
                  auth.createUserWithEmailAndPassword(
             email: email, password: password);
            return userCredential != null ? userCredential.user : null;
          } on FirebaseAuthException catch (e) {
           showToast(e.message);
          } catch (e) {
          log(e.toString());
           return null;
          }
       }

     Future<User> onLogin({String email, String password}) async {
      try {
        User user;
           await auth
        .signInWithEmailAndPassword(email: email, password: password)
      .then((value) {
        showToast("Login sucessful");
       user = value != null ? value.user : null;
      });
      return user;
     } on FirebaseAuthException catch (e) {
      showToast(e.message);
     }
    }

    sendResetPassword({String email}) async {
      bool isSent = false;
      try {
         await auth.sendPasswordResetEmail(email: email).then((value) {
           showToast("Reset password email sent");
            isSent = true;
        });
        return isSent;
       } on FirebaseAuthException catch (e) {
           showToast(e.message);
    }
  }

    Future<void> onAuthStateChanged(FirebaseUser user) async {
     if (user == null) {
       _status = Status.Unauthenticated;
        } else {
        _user = user;
        _status = Status.Authenticated;
       }
       notifyListeners();
     }

     Status get status => _status;

     set status(Status value) {
        _status = value;
        }
   }

看看他们如何直接在 firebase_auth 代码中进行测试:https://github.com/FirebaseExtended/flutterfire/tree/master/packages/firebase_auth/firebase_auth/test

致电setupFirebaseAuthMocks(您可以调整代码here) 方法在你的开头main方法和调用await Firebase.initializeApp(); in a setUpAll method.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Firebase身份验证单元测试错误没有Firebase应用程序 的相关文章

随机推荐

  • 如何使用 PlaySound() 或任何基本函数/方法在 C++ 中同时播放超过 1 个 .wav 声音?

    我正在尝试制作一款游戏 我需要同时播放许多声音 我知道 v basic 或者只是知道功能 PlaySound to run wav声音 问题在于SND ASYNC我无法同时播放多个声音 但首先播放的声音会在中间跳过并播放下一个声音 有什么方
  • 无法解析符号“持久性”

    我对 Java SpringBoot 和 MySQL 都很陌生 我还在上课 所以这些对我来说没有任何意义 我没有尝试过任何事情 因为我什至不知道从哪里开始 我以为我拥有所有正确的依赖项 但是当我在 Event java 中突出显示红色问题灯
  • mp3 长度(以毫秒为单位)

    我需要一个脚本或命令行工具来获取 mp3 长度 以毫秒为单位 这些文件是用 lame 编码的 64 kbits mono cbr 我为我选择的语言 ruby 寻找了 libmad 但没有发现任何值得注意的东西 def self get au
  • 如何在C++中使用fft生成音频频谱? [关闭]

    Closed 这个问题需要多问focused 目前不接受答案 我想生成一个音频频谱 如这个视频 的 mp3 音频文件 基本上这个问题需要计算音频信号的 fft 我如何用 C C 编程 我查看了几个开源库 例如FFTW我真的不知道如何使用这些
  • 带有 jQ​​uery UI DatePicker 值的 ASP.NET 文本框在回发时丢失

    我有一个在 ASP NET 文本框控件上使用 jQuery UI DatePicker 的应用程序 该控件按预期工作 但我注意到当您从服务器调用回发 通过提交按钮 时 输入的值会在应用程序中丢失 想知道大家有没有经历过这种情况 您必须采取哪
  • Azure Devops Git 分支区分大小写

    当我通过 Azure Devops 门户查看我的分支时 我注意到我有以下内容 feature feature1 Feature feature2 通过我的 git 客户端 Fork 在本地看起来是正确的 feature feature1 f
  • 问:解决Java中的almostIncreasingSequence问题(Codefights)

    我无法通过最后的隐藏测试 你能告诉我我错过了什么吗 提前谢谢 以下是语句 给定一个整数序列作为数组 确定是否可以通过从数组中删除不超过一个元素来获得严格递增序列 boolean almostIncreasingSequence int se
  • 使用非托管代码使用扩展名获取文件图标时在 x86 系统上出现异常

    我正在开发磁盘目录应用程序 需要我使用从数据库检索的文件扩展名来获取文件图标 使用其扩展名获取文件图标的代码在具有任何 CPU 调试配置的 Windows 7 x64 计算机上工作得非常好 但是当我在调试配置中切换到 x86 时 我收到以下
  • 适用于 Chrome 扩展的 Azure AD 应用重定向 URI

    我正在使用适用于 JavaScript 的 Microsoft 身份验证库 MSAL js 版本1 3 2在我的基于 React JS 的 chrome 扩展中 我需要支持两个登录场景 以便获得在应用程序的其余部分中使用的不记名令牌 pro
  • 使用 CSS 添加虚线间隔/填充

    我正在一家餐厅网站上工作 该设计要求在菜单项和价格之间使用典型的虚线填充 我已经在网上搜索并弄乱了它一个小时左右 但似乎找不到任何仅使用 CSS 来做到这一点的好方法 我在这里发现了一些其他解决方案 如果您有纯色背景 它们效果很好 但是在这
  • 如何在 ChartJS 中排序、插入和更新完整数据集?

    我在使用 ChartJS 时遇到一些问题 简单的更新方法无法解决 我想知道是否有一个选择 轻松地对数据集进行排序 在两点之间插入一些数据 重新加载整个图表而不用替换画布 全新的图表 没有内置选项 但使用以下命令编写自己的选项非常容易addD
  • catch 和finally 中return 语句的行为

    请参阅以下代码并解释输出行为 public class MyFinalTest public int doMethod try throw new Exception catch Exception ex return 5 finally
  • Python:为列表或对象中的变量赋值[重复]

    这个问题在这里已经有答案了 我想做以下事情 a 1 b 2 c 3 tom a b c for i in tom i 6 期望的结果是a 6 实际结果是a 1 我猜想如果没有某种执行程序就没有办法做到这一点 正确的 最初我误解了你的问题 我
  • Codeigniter:更新图像和显示

    我遇到了更新图像的问题 我已经创建了图像上传 效果很好 但我也希望对其进行更新 当我添加需要的图像时 它会正确更新 但如果我不想更改图像并保持原样 则无法检索我当前的图像 请帮我 控制器 public function insert dat
  • 元数据和微观数据有什么区别?

    我对这两个术语感到很困惑 我知道元数据的基本含义是 关于数据的数据 微观数据是指网页现在更容易被搜索引擎访问 但这两个术语的区别是什么 微观数据是特定技术的名称 metadata是一个通用术语 正如您所解释的 元数据是关于数据的数据 我们通
  • 具有重复项的类的多标签编码

    如何对具有重复项的列表列进行 n hot 编码 就像是MultiLabelBinarizer来自 sklearn 它计算重复类的实例数量而不是二值化 输入示例 x pd Series a b a b c c c 预期输出 a b c 0 2
  • 序列化数组时删除 根元素

    这是一个代码示例 public class Person public string FirstName get set public string LastName get set static void Main Person pers
  • 字节数组到 UIImage Objective-C

    我有一个字节数组 unsigned char outputData unsigned char malloc sizeof unsigned char w h 4 outputData y h 4 x 4 0 all alpha value
  • 我可以直接将地址分配给指针吗?如果是这样,该怎么做?

    int main int a 2 address is 0x7ffeefbff58c int b a std cout lt lt address of a lt lt b lt lt std endl return 0 我的 int 变量
  • Firebase身份验证单元测试错误没有Firebase应用程序

    我正在尝试测试我的firebase auth方法 身份验证方法有登录 注销 注册等 这是我想要执行单元测试的方法 我收到错误No Firebase App DEFAULT has been created call Firebase ini