代码之家  ›  专栏  ›  技术社区  ›  Jake Moritz

如何验证方法是否在模拟类的回调中运行?

  •  2
  • Jake Moritz  · 技术社区  · 7 年前

    我在Android代码中有一个实用程序类,用于处理用户身份验证。我正在用Mokcito为这个类编写单元测试,以验证监听器是否收到了创建新用户成功或失败的通知。以下是此实用程序类的方法之一:

    public void createNewUser(String email, String password) {
        firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnSuccessListener(authResult -> {
                    authListener.newUserCreated();
                })
                .addOnFailureListener(e -> {
                    authListener.failedCreatingNewUser();
                });
    }
    

    我在嘲笑你 FirebaseAuth 我想核实一下 authListener.newUserCreated() 已调用。我曾尝试使用深存根和参数捕获器来处理 firebaseAuth.createUserWithEmailAndPassword 但我不知道该怎么做。

    更新

    下面是我的测试类,其中包含此方法的测试:

    public class AuthUtilsTest {
    
        private static final String USERNAME = "USERNAME";
        private static final String PASSWORD = "PASSWORD";
    
        @Mock
        private FirebaseAuth firebaseAuth;
    
        @Mock
        private FirebaseFirestore firebaseFirestore;
    
        @Mock
        private BaseEncoding base64;
    
        @Mock
        private PreferencesRepo preferencesRepo;
    
        @Mock
        private AuthUtilsContract.EventListener eventListener;
    
        private AuthUtils authUtils;
    
        @Before
        public void setupAuthUtils() {
            MockitoAnnotations.initMocks(this);
    
            authUtils = new AuthUtils(
                    preferencesRepo,
                    firebaseAuth,
                    firebaseFirestore,
                    base64
            );
    
            authUtils.takeEventListener(eventListener);
        }
    
        @Test
        public void failureCreatingNewUserTellsListener() {
            Task<AuthResult> failedTask = Tasks.forException(new Exception("fail"));
            when(firebaseAuth.createUserWithEmailAndPassword(anyString(), anyString())).thenReturn(failedTask);
    
            authUtils.createNewUser(USERNAME, PASSWORD);
    
            verify(eventListener).failedCreatingNewUser();
        }
    
    }
    

    引发异常

    Java语言lang.ExceptionInInitializerError位于 通用域名格式。谷歌。安卓gms。任务。zzn。addOnSuccessListener(未知源) ... 原因:java。lang.RuntimeException:中的方法getMainLooper 安卓操作系统。活套未被嘲笑。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Jacob Botuck    7 年前

    使用Mockito。何时使createUserCall返回模拟任务。 然后是莫基托。验证任务以捕获add listener调用的参数。

    根据您的意愿测试捕获的参数(这就像单元测试中的单元测试,捕获的参数是您正在测试的新类)。

    此方法实际上不会测试是否调用了侦听器。只是调用了add listener方法,回调在调用时会执行它们应该执行的操作

    verify(mockTask).addOnSuccessListener(listenerCaptor.capture());
    OnSuccessListener<Auth> newObjectUnderTest = listenerCaptor.getValue();
    
    //ACT
    newObjectUnderTest.onSuccess(auth);
    
    //ASSERT
    verify(authListener).newUserCreated();
    
        2
  •  0
  •   Jacob Botuck    7 年前

    使用Mockito。何时使createUserCall返回已完成的 Task<AuthResult> .

    然后是莫基托。验证authListener是否执行了假设authListener也是模拟的应执行的操作